我有三个表:
表 1:帖子:id、uid、帖子、创建
表 2:用户:ID、用户名、电子邮件等
表 3:帖子点赞数: id、pid、uid
我希望创建一个查询,选择 10 个帖子以及每个帖子的用户名和点赞数。 我想要 0 表示没有喜欢的帖子。我已经在喜欢表中插入了一条记录,例如帖子 id 50。现在,我的查询的问题是,我得到 1 作为每个帖子的喜欢次数。
这是我的查询:
SELECT x.count as likes,
a.id,
a.uid,
a.post,
a.created,
b.username,
b.photo
FROM (
SELECT count(*) AS count
FROM postlikes AS c
JOIN posts AS d
ON c.pid=d.id
) x
JOIN posts AS a
JOIN user AS b
ON a.uid=b.id
LIMIT 0,10
最佳答案
这是一个需要 GROUP BY 的很好的例子。
select u.username
, p.created
, p.post
, p.id -- post_id
, p.uid -- user_id
, count(pl.pid) likes
from users u
join posts p on u.id = p.uid
left join postlikes pl on pl.pid = p.id
group by u.username
, p.created
, p.post
, p.id
, p.uid
关于mysql - 连接 3 个表 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21754909/