2016-03-16 157 views
0

表結構:優先選擇

報名:

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

和你的表模式是...?並且您當前的查詢是...? – Alex

+0

請您詳細說明一下嗎?這是相當模糊的你要求 – apomene

+0

我編輯了我的文章。如何根據費率類型值進行條件請求? – Mezoo

回答

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 
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'存在,然後顯示而不是其他人)將適當的列(「費率」,「類型」)拆分爲兩個使用case語句的新單獨列:第一列包含va爲F類型,第二個包含其他類型的值。我爲「類型」和「速度」列做了。然後,我使用group by,aggregation函數和IFNULL語句將這些列(和記錄)粘在一起(您可以在這裏使用其他語句:case,IF等)。

據我瞭解的問題,這是你所需要的。