3

I have table with a enum column with possible values of 'relative' and 'absolute'. There maybe duplicate rows with the difference being that column.

So normally I would select a row with the 'absolute' value but I need and if caluse to check if there is a 'duplicate' row where the column is 'relative' and then select that row instead (if there is a reletive row, there will always be absolute row too)

pseudo code:

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

4 回答 4

2

你可以试试这个:

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

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

编辑:

根据@Travesty3 的建议,我想强调一下,这个查询是在假设a 的基础上(non_unique_col + absolute_relative_col)进行的unique_col,它基于 OP 语句

可能有重复的行,不同之处在于该列

如果有相对行,也总会有绝对行

编辑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'
)
于 2013-08-02T12:04:46.630 回答
0

如果除了相对或绝对部分之外该行是相同的,并且如果您只需要每个 non_unique_column 值的行,为什么不简单地使用:

select non_unique_col, max(rel_or_abs), extra_data from tbl
group by non_unique_col;

http://sqlfiddle.com/#!2/b97fc0/2

于 2013-08-02T15:46:41.073 回答
0
SELECT * 
FROM table1 
INNER JOIN (
    SELECT non_unique_col nuc, 
           MAX(absolute_relative_col) rec 
    FROM table1 
    GROUP BY non_unique_col 
) AS t ON nuc=non_unique_col AND rec=absolute_relative_col
-- (@Zessx: second condition is still part of the INNER JOIN ...)

编辑

但我更喜欢 COALESCE 的想法(见上面草莓的评论!)好多了

SELECT * FROM table1 WHERE id IN ( 
 SELECT COALESCE(b.id,a.id) FROM tablel a 
 LEFT JOIN tbl b ON b.non_unique_col=a.non_unique_col
                AND b.absolute_relative_col='relative'
)
于 2013-08-02T12:27:40.837 回答
0

下面的(未经测试的)查询应该返回你想要的,但与大多数使用子查询的查询一样,我认为它不是很有效。

SELECT * 
FROM `table` 
WHERE `non_unique_col`=123 
AND ( 
    (`relativity` = 'relative') 
    OR (`relativity` = 'absolute' 
        AND NOT EXISTS (
            SELECT 1 
            FROM `table` 
            WHERE `non_unique_col`=123 
            AND `relativity`='relative'
        )
    )
);

请参阅本文档

编辑:如果您想创建一个列表(例如,没有 id),那么您将编写如下内容:

SELECT * 
FROM `table` as a 
WHERE (`relativity` = 'relative') 
OR (
    `relativity` = 'absolute' 
    AND NOT EXISTS (
        SELECT 1 
        FROM `table` as b 
        WHERE a.`non_unique_col`=b.`non_unique_col` 
        AND `relativity`='relative'
    )
);
于 2013-08-02T12:18:06.720 回答