使用两个内加入MySQL查询
我有两个表像下面的图片:使用两个内加入MySQL查询
用户表:
offer_comments
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");
但它返回[]
!
试试这个:
$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
如果我想在php代码中读取u.name和u.family,我该怎么办?评论'=> $ a_comment - > ???? – 2014-09-21 13:32:21
我不使用PHP,所以我不能帮你。我只是指出了SQL关系的问题:) – Milen 2014-09-21 13:34:09
你有更多的一列称为你的派生表中有'id'('e')? '选择此优惠。* ..'从来都不是一个好方法,尝试指定每一列,而不是(或免得你需要的那些) – Milen 2014-09-21 13:25:01
好吧,我需要ID offer_id user_id说明 评论 quet 确认。 – 2014-09-21 13:27:13