我需要通过一个查询为每个父母选择有孩子的父母和孩子的数量。 现在我使用下一个查询:
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
我想我做错了......是吗?
答案 0 :(得分:1)
您的解决方案应该可以正常工作,但是table_a
的每一行都会执行子选择,这使得它成为非最佳解决方案。一个更好的解决方案是JOIN
两个表,并使用GROUP 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
答案 1 :(得分:1)
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