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

时间:2014-09-21 13:15:30

标签: mysql sql

我有两张桌子,如下图:

用户表:

enter image description here

offer_comments

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");

但它会返回[] !!

1 个答案:

答案 0 :(得分: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派生表中,usersoffer_comments之间的关系应为users.id = offer_comments.user_id,您已完成users.id = offer_comments.id