MySQL根据优先级逻辑选择唯一记录

时间:2015-11-27 21:01:59

标签: mysql sql distinct

我的表ITEM包含以下列:id,status,hash,value。 如果我有以下记录:

1, "NEW", 111111, "value1"
2, "BOOKMARKED", 111111, "value2"
3, "PREPARING", 111111, "value3"
4, "NEW", 222222, "value4"
5, "BOOKMARKED", 222222, "value5"
6, "NEW", 333333, "value6"

我需要获得具有以下逻辑的记录: 如果HASH列相同则只返回一条记录。 “PREPARING”优先于“BOOKMARKED”,“BOOKMARKED”优先于“NEW”。

因此查询结果将返回:

3, "PREPARING", 111111, "value3"
5, "BOOKMARKED", 222222, "value5"
6, "NEW", 333333, "value6"

谢谢。

2 个答案:

答案 0 :(得分:2)

一种方法是根据规则枚举值,然后取第一个值:

select t.*
from (select t.*,
             (@rn := if(@h = hash, @rn + 1,
                        if(@h := hash, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @rn := 0, @h := '') params
      order by hash,
               field(status, 'PREPARING', 'BOOKMARKED', 'NEW')
     ) t
where rn = 1;

答案 1 :(得分:1)

这是有效的,您可以在案例结构中更改优先级:

select  `ITEM`.*
from `ITEM`
inner join 
(
  SELECT `ITEM`.`hash`,
    max(
      CASE `ITEM`.`status` 
        WHEN 'PREPARING' THEN 2
        WHEN 'BOOKMARKED' THEN 1
        ELSE 0 
      END
    ) as `g`
  FROM `ITEM`
  group by `ITEM`.`hash`
) as `t` ON 
  `t`.`hash` = `ITEM`.`hash` AND
  `t`.`g` = (
    CASE `ITEM`.`status` 
        WHEN 'PREPARING' THEN 2
        WHEN 'BOOKMARKED' THEN 1
        ELSE 0 
    END
  )