我有以下列的表项: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"
我需要用以下逻辑获取记录:
如果哈希列相同,则只返回一条记录。“准备“优先于”和“优先”优先于“新”。
所以查询结果将返回:
3, "PREPARING", 111111, "value3"
5, "BOOKMARKED", 222222, "value5"
6, "NEW", 333333, "value6"
谢谢您。
最佳答案
一种方法是根据规则枚举值,然后获取第一个值:
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;
关于mysql - MySQL根据优先级逻辑选择唯一记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33964740/