按优先级选择

时间:2016-03-16 13:07:05

标签: mysql sql

表格结构:

注册:

uuid | name | total

评分:

uuid | type | rate

Registration_Rate:

registration | rate

初始请求是:

select * from registration r
join registration_rate rr on rr.registration = r.uuid
join rate rt on rt.uuid = rr.rate
group by r.name,  rt.type

来自两个表(注册和费率)的我的SQL结果是:

  uuid | name | rate | type
     1 | AAA  | 15   | U
     2 | BBB  | 20   | U
     3 | CCC  | 300  | F
     4 | AAA  | 250  | F

我想有这样的东西(如果存在费率类型'F'则显示相反)

  uuid | name | rate | type
     2 | BBB  | 20   | U
     3 | CCC  | 300  | F
     4 | AAA  | 250  | F

由于

已编辑:

我尝试了另一种有效的解决方案

select uuid, name, rate, (case rt.type when 2 then 2 else 1 end ) as type
from registration r
join registration_rate rr on rr.registration = r.uuid
join rate rt on rt.uuid = rr.rate
group by r.name,  rt.type

2 个答案:

答案 0 :(得分:0)

如果是F行则返回它。或者,使用NOT EXISTS验证没有其他具有相同名称的行具有F。

select t1.*
from tablename t1
where type = 'F'
   or not exists (select * from tablename t2
                  where t2.name = t1.name
                    and t2.type = 'F')

替代解决方案:

select t1.*
from tablename t1
    join (select name, min(type) type
          from tablename
          group by name) t2
    ON t1.name = t2.name and t1.type = t2.type

答案 1 :(得分:0)

试试这个(我建议主要想法)

 SELECT t.uuid, 
       t.name, 
       IFNULL(MAX(t.F_type), MAX(t.not_F_type)) AS "type", 
       IFNULL(MAX(t.F_rate), MAX(t.not_F_rate)) AS "rate"
FROM
(
    SELECT r.uuid, 
           r.name,
           CASE rt.type WHEN 'F' THEN rt.type END AS F_type, 
           CASE WHEN rt.type <> 'F' THEN rt.type END AS not_F_type,
           CASE rt.type WHEN 'F' THEN rt.rate END AS F_rate, 
           CASE WHEN rt.type <> 'F' THEN rt.rate END AS not_F_rate
    FROM registration AS r
    JOIN registration_rate AS rr ON rr.registration = r.uuid
    JOIN rate AS rt ON rt.uuid = rr.rate
) as t
GROUP BY t.uuid, t.name;

因此,您需要根据您的规则(如果比率的类型'F'存在,然后显示而不是其他)将适当的列(“rate”,“type”)拆分为使用case语句的两个新的单独列:第一个column包含F类型的值,第二列包含其他类型的值。我为“type”和“rate”列做了这个。然后我使用group by,aggregation functions和IFNULL语句将这些列(和记录)粘在一起(你可以在这里使用其他语句:case,IF等)。

据我所知,这就是你所需要的。