2014-09-21 115 views
0

我有两个表像下面的图片:使用两个内加入MySQL查询

用户表:

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 ; 
} 

现在,我想用inner join代替offer_comments,我该怎么办? 我想改用的offer_comments下面的SQL:

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

你有更多的一列称为你的派生表中有'id'('e')? '选择此优惠。* ..'从来都不是一个好方法,尝试指定每一列,而不是(或免得你需要的那些) – Milen 2014-09-21 13:25:01

+0

好吧,我需要ID offer_id user_id说明 评论 quet 确认。 – 2014-09-21 13:27:13

回答

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

+0

如果我想在php代码中读取u.name和u.family,我该怎么办?评论'=> $ a_comment - > ???? – 2014-09-21 13:32:21

+0

我不使用PHP,所以我不能帮你。我只是指出了SQL关系的问题:) – Milen 2014-09-21 13:34:09