Php Mysql加入两个包含多个编码和空记录的表

时间:2015-09-22 12:00:32

标签: mysql

我曾尝试从2个表中获取记录,但它没有显示所需的输出,其中我的第一个表是ttreply

ttreply table

另一个表是ttreplycount,其中count存储如下:

ttreplycount

我试图获取值,但它没有获取记录,因为我想要我的mysql查询如下:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes,0) as Votes 
FROM `ttreply` r left join 
(SELECT sum(votes) as Votes from `ttreplyvotes` )x ON r.`post_id`=2 

这显示了我这样的输出:

Output

我需要的是这样的:

id  userid    reply                Votes
2   3       Testing 2nd reply      -2
3   3       Testing 3nd reply       0
4   3        rewsf                  0

任何帮助都会有所帮助。

1 个答案:

答案 0 :(得分:2)

您可以通过将条件移动到where子句来获取所需的行:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes,0) as Votes 
FROM `ttreply` r cross join 
     (SELECT sum(votes) as Votes from `ttreplyvotes` ) x 
WHERE r.`post_id` = 2 ;

这三行都有-2。为什么你只需要一行总数?你如何确定哪一行得到总数?

编辑:

哦,我想我明白了:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes, 0) as Votes 
FROM `ttreply` r left join 
     (SELECT replyid, sum(votes) as Votes
      FROM `ttreplyvotes`
      GROUP BY replyid
     ) x 
     ON x.replyid = r.id
WHERE r.`post_id` = 2 ;