mysql如何用sql查询两个表并从第二个表计算groupid

zbwhf8kr  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(319)

我正在尝试创建一个sql,从第一个表“posts\u main”获取所有数据,然后从第二个表“posts\u comments”获取注解计数
我试过:

$sql = "SELECT * FROM posts_main, count(posts_comments.groupid)
INNER JOIN posts_comments ON posts_comments.groupid = posts_main.id
WHERE posts_main.user_id = '$user_id'
GROUP BY posts_main.id";

拜托,我怎么做?
谢谢。。。。

4xrmg8kj

4xrmg8kj1#

尝试下面的查询。

$sql = "select posts_main.*, 
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_group 
from posts_main 
WHERE posts_main.user_id = '$user_id' ";
bybem2ql

bybem2ql2#

用子查询试试这个

SELECT posts.*,cnt FROM posts_main  
INNER JOIN (select posts_comments.groupid,count(posts_comments.groupid) as cnt
group by posts_comments.groupid)a
ON a.groupid = posts_main.id
WHERE posts_main.user_id = '$user_id'

相关问题