我有两张表如下:
table_a: id, title
table_b: id, table_a_id, status
我想为table_a的每个值选择table_b中的条目总数,以及table_b中不引用table_a的条目总数。
例如,假设table_a具有值:
{id, title}
(1, "Value 1")
(2, "Value 2")
(3, "Value 3")
和table_b具有以下条目
{id, table_a_id, status}
(1, 1, 'open')
(2, 1, 'closed')
(3, -, 'open')
(4, 2, 'closed')
我想要得到的是:
("Value 1", 2)
("Value 2", 1)
("Value 3", 0)
(-, 1)
如果没有空值,我可以将其写为:
SELECT table_a.id, table_a.title, count(table_b.id)
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.table_a_id
GROUP BY table_a.id, table_a.title
但是,这并没有给出table_b中那些不引用table_a的条目的值。如果我反转连接,那么我可以从table_b获取所有值,但不能从table_a获取。如何在一个查询中同时获得这两个?
答案 0 :(得分:2)
我正在使用SQL Server,但我想它也可以在MySQL上正常运行。这里最重要的是COALESCE
函数and MySQL runs it the same way SQL Server does。
SELECT COALESCE(a.title, '-'), COUNT(b.id)
FROM #table_b b
LEFT JOIN #table_a a ON b.table_a_id = a.id
GROUP BY a.title
UNION
SELECT a.title, 0
FROM #table_a a
LEFT JOIN #table_b b ON b.table_a_id = a.id
WHERE b.id IS NULL
答案 1 :(得分:1)
尝试类似
的内容SELECT
table_a.id,
count(table_b.id)
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.table_a_id
GROUP BY table_a.id
UNION
SELECT
table_a_id,
count(table_b.id)
FROM table_b
WHERE table_a_id not in (
SELECT id from table_a
)
GROUP BY table_a_id