在mysql查询中使用两个内连接

问题描述 投票:0回答:1

我有两张桌子,如下图所示:

用户表:

enter image description here

报价_评论

enter image description here

offer_comments
表存储评论和评论的答案。 通过使用下面的功能,我可以根据
$id
获取评论并回答评论。

function getCommentsAnItem($id){

    mysql_query("SET CHARACTER SET utf8");
    $result_comments = mysql_query("select e.comment as comment,m.comment as answer_to_comment 
    from offer_comments e 
    inner join offer_comments m on e.id = m.quet 
    where e.offer_id=$id and e.confirm=1");
    $comments = array();
    while($a_comment=mysql_fetch_object($result_comments)){

        $comment = array(
        'comment'=>$a_comment->comment,
        'answer'=>$a_comment->answer_to_comment
        );
        array_push($comments,$comment);
    }

    return $comments ;
}

现在,我想使用内连接而不是

offer_comments
,我该怎么办? 我想使用下面的 sql 而不是
offer_comments
:

select offer.*,u.id,u.name,u.family from offer_comments offer
        inner join users u on offer.id=u.id

喜欢:

    $result_comments = mysql_query("select e.comment as comment,m.comment as answer_to_comment 
    from (select offer.*,u.name,u.family from offer_comments offer
    inner join users u on offer.id=u.id) e 
    inner join offer_comments m on e.id = m.quet 
    where e.offer_id=$id and e.confirm=1");

但它返回

[]
!!

sql mysql join subquery
1个回答
0
投票

试试这个:

   $result_comments = mysql_query("select e.comment as comment,m.comment as answer_to_comment 
    from (select offer.*,u.name,u.family from offer_comments offer
    inner join users u on offer.user_id=u.id) e 
    inner join offer_comments m on e.id = m.quet 
    where e.offer_id=$id and e.confirm=1");

这里的变化是在

e
派生表中,
users
offer_comments
之间的关系应该是
users.id = offer_comments.user_id
,你已经完成了
users.id = offer_comments.id

© www.soinside.com 2019 - 2024. All rights reserved.