简体   繁体   中英

MySQL Select unique record based on priority logic

I have table ITEM with following columns: id, status, hash, value. If I have following records:

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

I need to get records with following logic: if HASH column is same then return only one record. "PREPARING" has priority over "BOOKMARKED" and "BOOKMARKED" has priority over "NEW".

So result of query would return:

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

Thank you.

One method would be to enumerate the values according to the rules, and then take the first value:

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;

This is working, you can change priorities in case structures:

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
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM