[英]How to do this sql query for aggregating counts in a one-to-many relationship
我有兩個表,列表和globals_lists。 globals_lists基本上將list_id與global_id值相關聯。 我想為每個用戶的關聯列表類型獲取global_ids的計數(即globals_lists表中“很多”的數目)。
就像是:
select l.id, l.user_id, count(gl.global_id) as gl_count
from lists l, globals_lists gl
where l.list_type_id=10 and l.id=gl.list_id;
但這給了我錯誤的信息。
加:
GROUP BY l.id, l.user_id
在您的where
子句之后。
如果沒有GROUP BY
,那么您基本上只是在計算所有符合WHERE
和聯接條件的行,而無需考慮設置分組。 GROUP BY
將確保您正在執行每個用戶的計數匯總->列表組合。
select l.id, l.user_id, count(gl.global_id) as gl_count
from lists l, globals_lists gl
where l.list_type_id=10 and l.id=gl.list_id
GROUP BY l.id, l.user_id;
當使用諸如count
類的聚合函數時,應指定聚合應在其上進行操作的組。 MySQL不需要這樣做,但是如果這樣做,它總是很清楚。
在您的情況下,您要查找的組是(user_id, list_id)
。 您可以這樣編寫查詢:
select l.user_id
, l.id
, count(gl.global_id) as gl_count
from lists l
join globals_lists gl
on l.id = gl.list_id
where l.list_type_id = 10
group by
l.user_id
, l.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.