如果值不存在,如何显示0?

时间:2014-04-03 20:42:51

标签: mysql sql

我试图在不存在的值中显示0

我的信息:http://sqlfiddle.com/#!2/b1b77/3

|people|
  |client|  |sex|  |city_id|         
    MATT      1      1
    STEVE     1      2

|cities|
   |id|   |name|
     1      EEUU
     2      BRASIL 
     3      ARGENTINA
     4      JAPAN

我试图在city = 3和city = 4时显示一个值,如下所示:

|people|
   |client|  |sex|  |city_id|         
     0          0      0
     0          0      0

以下是查询:

SELECT  * FROM people
WHERE sex =1 AND city_id IN(3,4)

有人可以帮我这个吗? 感谢

2 个答案:

答案 0 :(得分:2)

您需要一张城市表,告诉您要显示数据的城市。然后从该城市表到您的人员表中进行OUTER JOIN


基于编辑:

select coelesce(p.client, '0') client, coalesce(p.sex,0) sex, coalesce(p.city_id, 0) city_id
from cities c
left join people p on p.city_id = c.id

我们仍然需要更好地了解您希望如何处理您拥有的数据。例如,我怀疑你想要按城市的客户进行分组,并显示总和或计数。

答案 1 :(得分:1)

您可以使用以下查询来获取所有城市的结果,其中包含' 0'对于没有关联人的城市的每一个价值。

SELECT  COALESCE(P.name, '0') AS client
        ,COALESCE(P.sex, '0') AS sex
        ,COALESCE(P.city, '0') AS city_id
FROM cities AS C
LEFT OUTER JOIN people AS P ON P.city = C.id;

从城市表中显示city_id可能更有意义,例如:

SELECT  COALESCE(P.name, '0') AS client
        ,COALESCE(P.sex, '0') AS sex
        ,C.id AS city_id
FROM cities AS C
LEFT OUTER JOIN people AS P ON P.city = C.id;

查看fiddle