gpt4 book ai didi

php - mysql multiple COUNT() from multiple tables with LEFT JOIN

转载 作者:可可西里 更新时间:2023-11-01 07:18:00 24 4
gpt4 key购买 nike

我想展示所有用户的结论。

我有 3 个表。

表格帖子

post_id(index)     user_id
1 1
2 3
3 3
4 4

table 照片

photo_id(index)     user_id
1 2
2 4
3 1
4 1

表格视频

photo_id(index)     user_id
1 4
2 4
3 3
4 3

表用户

user_id(index)     user_name
1 mark
2 tommy
3 john
4 james

事实上,每个表都有超过 4 行。

我想要这样的结果。

id     name      post    photo   videos
1 mark 1 2 0
2 tommy 0 1 0
3 john 2 0 2
4 james 1 1 2
5 .. .. .. ..

下面的代码是可以正常工作但速度很慢的 SQL,如果你能帮助我如何使用 LEFT JOIN,我将不胜感激。谢谢。

SQL

"select user.*, 
(select count(*) from post where post.userid = user.userid) postCount,
(select count(*) from photo where photo.userid = user.userid) photoCount,
(select count(*) from video where video .userid = user.userid) videoCount
from user order by user.id"

(或根据需要按 postCount、photoCount 或 videoCount ASC 或 DESC 排序)

我之前做过研究,但没有任何帮助。

最佳答案

    SELECT u.user_id, 
u.user_name,
COUNT(DISTINCT p.post_id) AS `postCount`,
COUNT(DISTINCT ph.photo_id) AS `photoCount`,
COUNT(DISTINCT v.video_id) AS `videoCount`
FROM user u
LEFT JOIN post p
ON p.user_id = u.user_id
LEFT JOIN photo ph
ON ph.user_id = u.user_id
LEFT JOIN video v
ON v.user_id = u.user_id
GROUP BY u.user_id
ORDER BY postCount;

Live DEMO

关于php - mysql multiple COUNT() from multiple tables with LEFT JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727235/

24 4 0