通过使用" join"来避免子查询" group by"

时间:2015-08-04 18:19:02

标签: mysql subquery

我试图避免使用子查询,但我无法获得正确的结果:

这是原始查询:

SELECT T1.IdL, T1.REG, T1.YearIn, T1.URL,
(SELECT Count(*) FROM T2 WHERE T1.IdL = T2.IdL) AS IdL_Count
FROM T1

以下是试图避免使用子查询,但由于T2中没有记录的行缺失,因此无效

SELECT T1.IdL, T1.REG, T1.YearIn, T1.URL, Count(*) AS IdL_Count
FROM T1 INNER JOIN T2 USING(IdL)
GROUP BY IdL

所以我尝试了LEFT JOIN,但我错了IdL_Count:1而不是0

有没有办法避免子查询?

2 个答案:

答案 0 :(得分:1)

无法避免子查询,至少没有指定的表结构(索引等)。 但是这个查询应该执行得更好

SELECT T1.IdL, T1.REG, T1.YearIn, T1.URL, coalesce(T3.count, 0) AS IdL_Count
FROM T1
LEFT JOIN (SELECT IdL, count(*) as count FROM T2 GROUP BY IdL) T3 on T3.IdL = T1.IdL

答案 1 :(得分:0)

我认为如果你做COUNT(T2。[somefield])而不是COUNT(*),它会在预期时返回0。如果这不起作用,您可以改为SUM(IF(T2.IdL IS NULL, 0, 1)) AS IdL_Count