如果数据集为空,MySQL将返回默认值

时间:2014-08-05 16:40:35

标签: mysql r select coalesce

我正在尝试使用以下方法查询数据库:

SELECT coalesce(value, "NA") as value 
FROM mytable FORCE INDEX (chrs) FORCE INDEX (sites) 
WHERE chrom = 1 AND site = 120

如果我在数据库中有一个条目,则此查询可以正常工作。但是,如果未找到该条目,则返回空数据集。我想更改查询,以便如果在数据库表中找不到它,它仍将返回某种值(对于"值")而不是空数据集

2 个答案:

答案 0 :(得分:1)

你如何添加UNION?

(   SELECT coalesce(value, "NA") as value 
    FROM mytable FORCE INDEX (chrs) FORCE INDEX (sites) 
    WHERE chrom = 1 AND site = 120
)
UNION ALL
(   SELECT 'NA' as value
    FROM mytable
    WHERE NOT EXISTS 
    (   SELECT coalesce(value, "NA") as value 
        FROM mytable FORCE INDEX (chrs) FORCE INDEX (sites) 
        WHERE chrom = 1 AND site = 120
    )
)

或者如果你想做一次合并,这样你就可以更容易地更改返回的部分,你可以像这样选择它。

SELECT COALESCE(value, "NA") as value
FROM
(   
    (   SELECT value
        FROM mytable FORCE INDEX (chrs) FORCE INDEX (sites) 
        WHERE chrom = 1 AND site = 120
    )
    UNION ALL
    (   SELECT NULL as value
        FROM mytable
        WHERE NOT EXISTS 
        (   SELECT value as value 
            FROM mytable FORCE INDEX (chrs) FORCE INDEX (sites) 
            WHERE chrom = 1 AND site = 120
        )
    )
) t

DEMO

答案 1 :(得分:0)

一种(丑陋的)方法:创建一个只有一行的表(与该表中的数据无关),然后使用:

SELECT coalesce(m.value, "NA") from oneline left join mytable m on m.chrom=1 and m.site=120;

这是你得到的:

mysql> select * from oneline;
+------+
| id   |
+------+
|    1 |
+------+
1 row in set (0,00 sec)

mysql> select * from mytable;
+-------+-------+------+
| value | chrom | site |
+-------+-------+------+
| test  |     1 |  120 |
+-------+-------+------+
1 row in set (0,00 sec)

mysql> SELECT coalesce(m.value, "NA") from oneline left join mytable m on m.chrom=1 and m.site=120;
+-------------------------+
| coalesce(m.value, "NA") |
+-------------------------+
| test                    |
+-------------------------+
1 row in set (0,00 sec)

mysql> SELECT coalesce(m.value, "NA") from oneline left join mytable m on m.chrom=1 and m.site=119;
+-------------------------+
| coalesce(m.value, "NA") |
+-------------------------+
| NA                      |
+-------------------------+
1 row in set (0,00 sec)