基于Prority值的MySQL行

时间:2018-04-22 18:35:33

标签: mysql sql

假设我有一个包含四列的表:FirstName,LastName,Number(不是主键)和Status。如果有一个人具有相同的名字,姓氏和号码,但状态不同(状态是一个字符串,如" King"或" Queen"或"杰克"。)

我想从表中检索所有列的所有值,但是如果有重复项,那里有相同的名字,姓氏和数字,我想得到状态为" King",如果没有" King"状态然后得到那些"女王"如果与#34; King"没有重复或"女王"而不只是获得其中一个与杰克"。

基本上,优先顺序是King,Queen,然后是Jack。所以,我想要从表中的所有值,但如果有重复项只包括具有最高优先级的值。我做了一些研究,似乎除了MYSql之外的SQL实现提供了诸如dense_rank之类的函数,但是我需要在MYSql中实现它,我找不到任何方法。

2 个答案:

答案 0 :(得分:0)

执行此操作的一种方法涉及union all

select t.*
from t
where t.status = 'King'
union all
select t.*
from t
where t.status = 'Queen' and
      not exists (select 1 from t t2 where t2.name = t.name andt2.status in ('King'))
union all
select t.*
from t
where t.status = 'Jack' and
      not exists (select 1 from t t2 where t2.name = t.name and t2.status in ('King', 'Queen'));

另一种方法使用相关子查询:

select t.*
from t
where (name, field(t.status, 'King', 'Queen', 'Jack')) in
          (select t2.name, max(field(t2.status, 'King', 'Queen', 'Jack'))
           from t t2
           where t2.status in ('King', 'Queen', 'Jack')
           group by t2.name
          );

答案 1 :(得分:0)

尝试使用会话变量:

SET @row_number:=1;

SELECT
    FirstName,
    LastName,
    Number,
    Status
FROM(
    SELECT 
        @row_number:=
        CASE
            WHEN @FirstName = FirstName AND @LastName = LastName AND @Number = Number
            THEN @row_number + 1
            ELSE 1
        END AS num,
        @FirstName := FirstName as FirstName,
        @LastName := LastName as LastName,
        @Number := Number as Number,
        Status
    FROM
        t1
    ORDER BY 
        FirstName,
        lastName,
        Number,
        CASE 
            WHEN STATUS = 'King' THEN '1'
            WHEN STATUS = 'Queen' THEN '2'
            WHEN STATUS = 'Jack' THEN '3'
        END
    ) as ttt
WHERE num = 1;