gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:39:37 26 4
gpt4 key购买 nike

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

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

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

最佳答案

你加一个 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
)
)

或者如果您想进行一次合并,这样您就可以更轻松地更改返回的部分(如果为 null),您可以像这样从中进行选择。

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

关于如果数据集为空,MySQL 返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25144075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com