Mysql LEFT JOIN返回null值

时间:2013-07-03 20:01:30

标签: mysql

SELECT t1.id, t1.name, t1.population, CAST(SUM(t2.town_1) AS CHAR) AS town, CAST(SUM(CASE WHEN t2.id LIKE 23 THEN 1 ELSE 0 END) AS CHAR) AS population FROM area1 t1 LEFT JOIN area2 t2 ON t1.id = t2.id WHERE t1.id like 23

通常,如果两个表中都存在id = 23,它将匹配。但情况并非如此(不在t1表中),因此请求返回NULL值。
如何才能返回没有结果?

1 个答案:

答案 0 :(得分:7)

如果您只希望在BOTH表中存在ID时匹配结果,那么您正在寻找INNER JOIN而不是LEFT JOIN。


修改

第二个想法,这是因为你的聚合函数(SUM)。你把它们作为CHAR投射(甚至不知道你能做到这一点)。您应该使用GROUP BY。试试这个:

SQL Fiddle

SELECT
  t1.id,
  t1.name,
  t1.population,
  SUM(t2.town_1) AS town,
  SUM(CASE WHEN t2.id LIKE 23 THEN 1 ELSE 0 END) AS population
FROM
  area1 t1
  INNER JOIN area2 t2
    ON t1.id = t2.id
WHERE
  t1.id like 23
GROUP BY
  t1.id,
  t1.name,
  t1.population

在旁注中,WHERE子句中不需要like。你拥有它的方式,就像=符号一样。