作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个带有枚举列的表,可能的值为“相对”和“绝对”。可能存在重复的行,不同之处在于该列。
所以通常我会选择具有“绝对”值的行,但我需要并且是否需要检查列是否为“相对”的“重复”行,然后选择该行(如果有相对行,总会有绝对行)
伪代码:
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/
我是一名优秀的程序员,十分优秀!