如何合并这两个SQL查询?

时间:2015-01-30 18:48:10

标签: php mysql database

架构:http://pastebin.com/jU3HmmNM

$mainfetch = "SELECT * FROM status ORDER BY status_id DESC LIMIT 10,0";

while($mainfetch -> $result) {
  $subquery = SELECT COUNT(*) FROM status s, likes l WHERE s.status_id = l.status_id AND l.member_id = 1;
$liked = $query->row();
if($liked > 0) {
//liked
}else {
//not liked
}
}

所以这不是最优的,因为$ subquery每次都会执行10次,我希望将$子查询添加到$ mainfetch,我怎么能加入它们呢?

2 个答案:

答案 0 :(得分:0)

你只需要在s.status_id = l.status_id添加一个左连接...然后你也得到l.status_id:如果它是null,那么成员1不喜欢它,否则当然是。< / p>

答案 1 :(得分:0)

使用您提供的架构:

SELECT s.status_id, s.text_id, count(l.status_id) as like_count
FROM status AS s LEFT JOIN likes AS l ON (s.status_id = l.status_id AND l.member_id = 1) 
group by s.status_id, s.text_id
ORDER BY status_id DESC
LIMIT 10,0