3

鉴于:

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
4

2 回答 2

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

似乎工作

于 2012-12-04T00:16:22.330 回答
4

我相信你正在寻找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
...

希望这可以帮助。

于 2012-12-04T00:01:31.967 回答