gpt4 book ai didi

MySQL IF THEN 在 WHERE 子句中

转载 作者:可可西里 更新时间:2023-11-01 08:34:15 25 4
gpt4 key购买 nike

我有一个带有枚举列的表,可能的值为“相对”和“绝对”。可能存在重复的行,不同之处在于该列。

所以通常我会选择具有“绝对”值的行,但我需要并且是否需要检查列是否为“相对”的“重复”行,然后选择该行(如果有相对行,总会有绝对行)

伪代码:

select *
from table
where non_unique_col = 123
and IF (has result row with 'relative'
then return that row
else return 'absolute' row)

最佳答案

你可以试试这个:

SELECT *
FROM `table`
WHERE `non_unique_col` = 123
ORDER BY `absolute_relative_col` DESC
LIMIT 1

这样,如果只有一个结果,没问题,如果有更多,你会得到“相对”的结果。

编辑:

根据@Travesty3 的建议,我想强调这个查询是基于 (non_unique_col + absolute_relative_col) 生成一个 unique_col 的假设,它基于关于 OP 声明

There maybe duplicate rows with the difference being that column

if there is a relative row, there will always be absolute row too

编辑 2:

更通用的解决方案如下:

SELECT *
FROM `table` as t1
JOIN (
SELECT non_unique_col, absolute_relative_col
FROM `table`
WHERE `absolute_relative_col` = 'relative'
) as t2 USING (non_unique_col)
WHERE t2.absolute_relative_col = 'relative' OR (
t2.absolute_relative_col IS NULL
AND t1.absolute_relative_col = 'absolute'
)

关于MySQL IF THEN 在 WHERE 子句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016394/

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