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

标签 php mysql

我的情况是这样的:我有三个表: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/

相关文章:

php - 关于重复键更新值;两次插入相同的值

mysql - 按多个标签过滤帖子以返回具有所有这些标签的帖子,性能良好

javascript - 从数据库中随机调用图库图像,间隔重叠

PHP - 搜索特定文件的目录和子目录?

php - 如何在 Laravel 中手动返回或抛出验证错误/异常?

php - 调用未定义的方法 App\Http\Controllers\SubscriptionController::getMiddleware()

php - 用 json 返回一个 blob

php - 无法在 MySQL 中获取登录表单的哈希密码

phpDocumentor 到 wiki?

javascript - 使用框输入重定向页面