IF中的子查询作为具有空值的列的值

yos*_*ssi 3 mysql if-statement subquery

鉴于:

t1{id,type}
t2{type,table1_id}
Run Code Online (Sandbox Code Playgroud)

我正在使用这个:

SELECT IF(t1.type IS NULL, 'some default', t1.type) as ret from t1
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

SELECT IF(
    t1.type IS NULL, 
    IF(
        (SELECT t2.type FROM t2 WHERE t2.table1_id=t1.id LIMIT 1) IS NOT NULL,
        table2.type,
        'some defaults'
    ),
    t1.type
) as ret from table1
Run Code Online (Sandbox Code Playgroud)

fem*_*gon 6

这个 -

SELECT IF(
    t1.type IS NULL, 
    IF(
        (SELECT t2.type FROM t2 
           WHERE t2.table1_id=t1.id LIMIT 1)
           IS NOT NULL,
        t2.type,
        'some defaults'),
    t1.type
) as ret from t1, t2 where t1.id = t2.table1_id
Run Code Online (Sandbox Code Playgroud)

似乎工作.


Ker*_*mit 5

我相信你在找IFNULL.

IFNULL(expr1,expr2)

如果expr1不是NULL,则IFNULL()返回expr1; 否则它会返回expr2.IFNULL()返回数值或字符串值,具体取决于使用它的上下文.

哪个会将您当前的陈述转移到:

SELECT IFNULL(t1.type, 'some default') AS ret FROM t1 
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用CASE块.

SELECT
    (SELECT CASE
        WHEN t1.type IS NULL
            THEN 'some default'
        ELSE t1.type
    END AS ret) AS subq
...
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.