MySQL Select 基于优先级逻辑的唯一记录
MySQL Select unique record based on priority logic
我有 table 个包含以下列的 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 列相同,则 return 只有一条记录。 "PREPARING" 优先于 "BOOKMARKED","BOOKMARKED" 优先于 "NEW"。
所以查询结果会 return:
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;
这是可行的,您可以更改案例结构中的优先级:
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
)
我有 table 个包含以下列的 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 列相同,则 return 只有一条记录。 "PREPARING" 优先于 "BOOKMARKED","BOOKMARKED" 优先于 "NEW"。
所以查询结果会 return:
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;
这是可行的,您可以更改案例结构中的优先级:
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
)