gpt4 book ai didi

mysql - 如何更改此查询,以便在 select(*) 计数值为 2 时返回 true?

转载 作者:行者123 更新时间:2023-11-29 06:33:45 25 4
gpt4 key购买 nike

我不太喜欢 SQL,我有以下疑问。我有这个查询(我正在使用 MySql):

SELECT count(*)                                AS exist
FROM MeteoForecast AS MF
WHERE
MF.localization_id = 22
AND
DATE(MF.start_date) = DATE('2019/03/02')

将记录数返回到 MeteoForecast 表中作为 exist 字段。

我想这样修改:

如果count(*)的值等于2,则返回true(exist字段为true),否则返回exist 字段值为 false。

如何实现此行为?

最佳答案

您可以只使用 bool 表达式:

SELECT (count(*) = 2) AS exist2
FROM MeteoForecast mf
WHERE MF.localization_id = 22 AND
DATE(MF.start_date) = DATE('2019-03-02') ;

该表达式实际上返回 true 为“1”, false 为“0”。这些是 MySQL 中 bool 值 truefalse 的数字等价物。

假设 start_date 有时间部分,您应该将其写为:

SELECT (count(*) = 2) AS exist2
FROM MeteoForecast mf
WHERE MF.localization_id = 22 AND
MF.start_date >= '2019-03-02' AND
MF.stara_date < '2019-03-03' ;

这可以利用 MeteoForecast(localization_id, start_date) 上的索引,因此速度会快得多。

关于mysql - 如何更改此查询,以便在 select(*) 计数值为 2 时返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54960731/

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