[英]How to create Linq2Sql query that will group records from linked table and calculate 2 count fields
[英]Calculate count records from mysql group by fields
我在MySQL中的表格http://joxi.ru/5mdWRV8tyQzyr1
我的Programm Pass數組用戶
$ids = [1, 3, 7];
我查詢表:
SELECT responsible_id, count(id) as count
from test
WHERE active = 1
AND status = 3
AND responsible_id in (1, 3, 7)
GROUP BY responsible_id
ORDER BY count(id)
我得到結果http://joxi.ru/vAWYGq0IMxdjmW
但是,如果表上不存在該行,我還需要第一行帶有責任負責人ID = 7,計數為0。
要執行所需的操作,請使用left join
:
SELECT v.responsible_id, count(t.id) as count
FROM (SELECT 1 as responsible_id UNION ALL
SELECT 3 as responsible_id UNION ALL
SELECT 7 as responsible_id
) v LEFT JOIN
test t
ON t.responsible_id = v.responsible_id AND
t.active = 1 AND
t.status = 3
GROUP BY v.responsible_id
ORDER BY count(id);
請注意, WHERE
中的條件已移至ON
子句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.