[英]Group by and count data with one query
This is my table structure in database这是我在数据库中的表结构
I want to get number of likes for each post by counting post field in likes table and display it for every post using foreach
loop.我想通过计算喜欢表中的帖子字段来获得每个帖子的喜欢数量,并使用
foreach
循环为每个帖子显示它。
My question is我的问题是
Is there a way i can do this with one query with JOIN
, GROUP BY
and COUNT
tables and not create multiple queries.有没有一种方法可以通过一个带有
JOIN
、 GROUP BY
和COUNT
表的查询来做到这一点,而不是创建多个查询。
select p.id, p.title, p.content, count(l.id) as likes_count
from posts p
left join likes l on l.post = p.id
group by p.id, p.title, p.content
http://sqlfiddle.com/#!9/bca8ee/1 http://sqlfiddle.com/#!9/bca8ee/1
SELECT p.*, COUNT(l.id)
FROM posts p
LEFT JOIN likes l
ON l.post = p.id
GROUP BY p.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.