gpt4 book ai didi

php - 从 3 个表中选择并在 div 中回显结果

转载 作者:行者123 更新时间:2023-11-29 21:21:02 24 4
gpt4 key购买 nike

我的情况是这样的:我有三个表:user、search_queries 和 comments。

我想显示从这三个查询中获得的变量。

我对用户查询和搜索查询都使用了 INNER JOIN。这工作得很好。

但是如何从第三个表中获取变量?

下面是我到目前为止的代码。

<?php
$sql24 = "SELECT * FROM comments WHERE search_id=$search_id";
$result24=mysql_query($sql24);

$sql = "SELECT * FROM user INNER JOIN search_queries ON user.id = search_queries.id
ORDER BY search_id DESC";
$result=mysql_query($sql);

//-create while loop and loop through result set
while($row=mysql_fetch_array($result))
{
$fname =$row['fname'];
$sname=$row['sname'];
$id=$row['id'];
$email=$row['email'];
$profile_pic=$row['profile_pic'];
$city=$row['city'];
$country=$row['country'];
$search_date=$row['search_date'];
$QUERY=$row['QUERY'];
$search_id=$row['QUERY'];

//-display the result of the array
echo "the results from 2nd query ";
echo "the results from the 3rd query ";
}
?>

基础表中的字段:

  • 用户:ID、电子邮件、FNAME、SNAME、通行证、城市、个人资料图片等。
  • 评论:com_id、id、评论、日期等。
  • 搜索查询:search_id、id、QUERY、日期等。

相反,第一个选择查询似乎不起作用。

请帮忙。

最佳答案

好的,现在我们已经掌握了 3 个表的所有必需信息。简单总结一下:

  • 您想要列出所有帖子(search_queries 表)以及所有评论 - 无论帖子是否有评论,都无关紧要。您还想显示帖子和评论的用户详细信息。
  • 所有 3 个表中的 id 字段均标识用户
  • 评论表中有一个 search_id 外键,用于标识评论所属的帖子

sql 查询如下所示:

select u1.id as poster_id, --user id for the post
u1....,--whatever other field(s) you would like to include about the user, who created the post, alias each of them
u2.id as commenter_id, --user id for the comment
u2....,--whatever other field(s) you would like to include about the user, who created the comment, alias each of them
s.search_id, -- id of the post
s...., --whatever other field(s) you would like to include about the post
c.com_id, -- id of the comment
c...., --whatever other field(s) you would like to include about the comment
from search_queries s
left join comments c on s.search_id=c.search_id --left join ensures that all posts are listed, not just the ones with comments
inner join user u1 on s.id=u1.id --join to user table to get user details for the poster
left join user u2 on c.id=u2.id --join to get the user details of the commenter, note that I used left join again

如果您只想获取单个帖子的详细信息,请在 where 条件中提供 search_id。

我会让你自己弄清楚 php 代码。但是,请注意,您不应再使用 mysql_*() 函数,而应使用 mysqli 或 pdo。

关于php - 从 3 个表中选择并在 div 中回显结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35722768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com