MySQL IF NOT NULL,然后显示1,否则显示0


104

我在这里处理一些显示问题。我确定我只是忽略了IF / ELSE功能。

我要查询2个表(客户,地址)。第一个具有主记录,但是第二个可能具有记录,也可能没有记录到LEFT JOIN。

如果地址表中没有记录,我想显示零。如果记录存在,我只想显示1。

到目前为止,我已经尝试过:

SELECT c.name, COALESCE(a.addressid,0) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123

第一个示例不这样做。但是我可能在使用COALESCE时出错。

如何显示0(如果为null)和1(如果存在)?


Answers:


211

代替COALESCE(a.addressid,0) AS addressexists,使用CASE

CASE WHEN a.addressid IS NOT NULL 
       THEN 1
       ELSE 0
END AS addressexists

或更简单:

(a.addressid IS NOT NULL) AS addressexists

之所以有效,TRUE是因为1在MySQL和中显示FALSE0


96
SELECT c.name, IF(a.addressid IS NULL,0,1) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123

17

如果您来自C / C ++,请注意以下事项:

select if(name, 1, 0) ..

即使'name'不是NULL,与C中的情况不同,也会触发错误条件,并且上述语句返回0。因此,您必须记住明确检查NULL或空字符串:

 select if(name is null or name = '', 0, 1)

上面PS PS Eugen的例子是正确的,但我想澄清一下这一细微差别,因为它使我感到惊讶。


16
SELECT 
    c.name, 
    CASE WHEN a.addressid IS NULL THEN 0 ELSE 1 END AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123

2

没有WHERE的另一种方法,请尝试此。

将同时选择Empty和NULL值

SELECT ISNULL(NULLIF(fieldname,''))  FROM tablename

如果它是一个空字符串,它将设置为null,然后在它上也为true。


也有用:从表名中选择IFNULL(fieldname,“ 1”);
PodTech.io


0

如果在TSQL中,可以尝试:

SELECT IIF(a.addressid IS NULL, 0, 1) AS addressexists

SQL Server应该可以工作

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.