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

时间:2012-12-03 23:56:27

标签: mysql if-statement subquery

假设:

t1{id,type}
t2{type,table1_id}

我正在使用它:

SELECT IF(t1.type IS NULL, 'some default', t1.type) as ret from t1

我想做这样的事情:

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

2 个答案:

答案 0 :(得分: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

似乎work

答案 1 :(得分:5)

我相信你正在寻找IFNULL

  

IFNULL(expr1,expr2)

     

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

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

SELECT IFNULL(t1.type, 'some default') AS ret FROM t1 

或者,您可以使用CASE块。

SELECT
    (SELECT CASE
        WHEN t1.type IS NULL
            THEN 'some default'
        ELSE t1.type
    END AS ret) AS subq
...

希望这有帮助。

相关问题