我有3张桌子
1.users
user_id nationality
1 Egyptian
2 Palestinian
3 French
id center_name
1 q
12 y
5 x
23 z
student_id center_id
1 12
2 5
3 5
1 23
2 12
我期待什么
Nationality center_name count_of_users_from this country
Egyptian y,z 10
Palestinian x,y 33
French x,q 7
我已经尝试了很多 mysql 查询,但我无法得到我想要的结果
我执行的最终查询:
SELECT * from (SELECT (LENGTH(GROUP_CONCAT(DISTINCT user_id))-ENGTH(REPLACE(GROUP_CONCAT(DISTINCT user_id), ',', ''))) as ss,GROUP_CONCAT( DISTINCT user_id) ,nationality from user where user_id in(SELECT student_id FROM `centers_users`) GROUP by nationality)a
但只能得到带有国籍的计数。
当我加入中心时给了我冗余,因为我不能用 group_concat 设置“ON”条件
我该如何实施?
谢谢..
我想你想加入表格并聚合:
select u.nationality,
group_concat(distinct c.center_name) as center_names,
count(distinct user_id) as users_from_this_country
from users u join
user_centers uc
on u.user_id = uc.student_id join
centers c
on c.center_id = uc.center_id
group by u.nationality;
您也许可以使用count(*)
for users_from_this_country
。这取决于您希望如何计算位于同一国家/地区多个中心的用户。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句