我需要通过一个查询为每个父母选择有孩子的父母和孩子的数量。现在我使用下一个查询:
SELECT table_a.*, (SELECT COUNT(*) FROM table_b WHERE table_b.LID=table_a.LID AND table_b.Yes=0) AS Co
FROM table_a
WHERE table_a.Ind>0 ORDER BY table_a.Ind ASC
我想我做错了......是吗?
您的解决方案应该可以工作,但是对于每一行都会执行子选择,table_a
使其成为非最佳解决方案。更好的解决方案是JOIN
两个表并使用 aGROUP BY
以更低的性能成本获得相同的结果。
SELECT table_a.LID
, COUNT(*) AS Co
FROM table_a
LEFT OUTER JOIN table_b ON table_b.LID = table_a.LID AND table_b.Yes = 0
WHERE table_a.Ind > 0
GROUP BY
table_a.LID
ORDER BY
table_a.Ind ASC
另外,在我看来,您应该始终为您的表设置别名,并使用该别名使语句更简洁、更易于阅读。
SELECT a.LID
, COUNT(*) AS Co
FROM table_a AS a
LEFT OUTER JOIN table_b AS b ON b.LID = a.LID AND b.Yes = 0
WHERE a.Ind > 0
GROUP BY
a.LID
ORDER BY
a.Ind ASC
你是对的 - 你做错了。即使它有效,但它是获得您喜欢的结果的错误方法。为了从一对多关系中获得总数,我们为此使用连接和分组:
SELECT a.ind, count(*) Total
FROM a JOIN b ON a.lid = b.lid
WHERE a.ind>0 AND b.yes = 0
GROUP BY a.ind
ORDER BY a.ind