[英]joining a SQL table with no value
I am doing a table join 我正在做表联接
SELECT b.type AS business,
b.business AS business,
b.city AS city
FROM businesses as b
JOIN cities AS c ON n.city = c.id;
My problem is that my table looks like this: 我的问题是我的桌子看起来像这样:
id type business city
1 1 2 4
2 4 5 2
3 2 3 0
So sometimes the rows will have the value of city as 0. However, with the table join if the city=0, id 3 would not be shown in the results. 因此,有时行的city值将为0。但是,如果city = 0,则使用表联接时,结果中将不会显示id 3。 As there is no city id of 0. Is there a way to rectify this using SQL?
由于没有城市ID为0。有没有办法使用SQL纠正此问题?
As eggyal suggested, your query could look something like this: 如Eggyal所建议,您的查询可能类似于以下内容:
SELECT b.type AS business,
b.business AS business,
CASE WHEN c.city IS NULL THEN 'N/A' ELSE c.city END AS city
FROM businesses as b
LEFT JOIN cities AS c ON b.city = c.id;
Using a CASE statement works but I think COALESCE is a little cleaner. 使用CASE语句是可行的,但我认为COALESCE会更干净一些。
SELECT b.type AS business,
b.business AS business,
COALESCE(c.city,'N/A') AS city
FROM businesses as b
LEFT JOIN cities AS c ON b.city = c.id;
As eggyal said, it's best to use NULL
values but if you're stuck using zeros you could add a NULLIF 如eggyal所说,最好使用
NULL
值,但是如果您使用零阻塞, 则可以添加NULLIF
SELECT b.type AS business,
b.business AS business,
COALESCE(NULLIF(c.city,0),'N/A') AS city
FROM businesses as b
LEFT JOIN cities AS c ON b.city = c.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.