gpt4 book ai didi

MySQL 数据透视表计数

转载 作者:行者123 更新时间:2023-11-29 11:28:44 25 4
gpt4 key购买 nike

我有三个表:

users
------
user_id
name

subjects
--------
subject_id
name

pivot_user_subject
------------------
user_id
subject_id

我有这个查询来显示主题和用户名:

SELECT a.name User, c.name Subject 
FROM users a, pivot_user_subject b, subjects c
WHERE a.user_id = b.user_id AND c.subject_id = b.subject_id;

效果很好。但现在我需要显示用户有多少个主题。

示例输出:

User      Subjects                      Subjects_count
Juan Math, Biology, Spanish 3
Rosa NULL 0
Rodrigo Math 1

知道如何仅使用 SQL 查询来完成该输出吗?谢谢。

最佳答案

试试这个

SELECT u.name, GROUP_CONCAT(s.name), COUNT(s.subject_id) as Subject_count
FROM users u
LEFT JOIN pivot_user_subject us ON u.user_id = us.user_id
LEFT JOIN subjects s ON s.subject_id = us.subject_id
GROUP BY u.user_id, u.name

SQL Fiddle

关于MySQL 数据透视表计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37772206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com