从3个表中选择并以div

时间:2016-03-01 12:20:37

标签: php mysql

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

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

我已经为用户和search_queries使用了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,email,fname,sname,pass,city,profile_pic等。
  • 评论:com_id,id,comment,date等。
  • search_queries:search_id,id,QUERY,date等。

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

请帮忙。

2 个答案:

答案 0 :(得分:0)

假设idcomments表中的search_queriesuser id

    $query = mysql_query("select * 
                            from user a, comments b, search_queries c
                            where a.id = b.id and a.id=c.id 
                            and c.search_id = '$search_id'");
    echo '<pre>';
    while($row=mysql_fetch_array($query)){
         print_r($row);
    }
    exit;

并尝试使用mysqli或PDO,因为不推荐使用mysql reason

答案 1 :(得分:0)

好的,现在我们拥有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。