我有两张桌子,如下图所示:
用户表:
报价_评论
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");
但它返回
[]
!!
试试这个:
$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