我有一张看起来像这样的表:
id | mid | oid
1 | 400 | 1
2 | 400 | NULL
3 | 401 | 1
4 | 403 | NULL
我正在尝试返回MID,null
OID的记录数和NOT null
oid的记录数
目前我正在使用它:
SELECT
(SELECT COUNT(id) FROM drp_ledger WHERE oid IS NULL) AS que,
(SELECT COUNT(id) FROM drp_ledger WHERE oid IS NOT NULL) AS finished,
`mid` FROM drp_ledger GROUP BY `mid`
然而,这会返回NULL
和NOT NULL
oid的整数。
所以我接着尝试使用JOIN
我觉得我很接近,但我不能让它发挥作用。
SELECT l.`mid`, que, finished FROM drp_ledger AS l
JOIN (SELECT COUNT(id) AS que FROM drp_ledger WHERE oid IS NULL GROUP BY `mid`) AS q ON q.`mid` = l.`mid`
JOIN (SELECT COUNT(id) AS finished FROM drp_ledger WHERE oid IS NOT NULL GROUP BY `mid`) AS f ON f.`mid` = l.`mid`
我想回复:
mid | que | finished
400 | 1 | 1
401 | 0 | 1
403 | 1 | 0
答案 0 :(得分:2)
无需加入!
SELECT
mid,
SUM(IF(oid IS NULL,1,0)) AS oid_null,
SUM(IF(oid IS NOT NULL,1,0)) AS oid_not_null
FROM tablename
GROUP BY mid
答案 1 :(得分:0)
您已关闭,但忘记在子查询中选择mid
。