2017-08-18 46 views
0

您好我有一個名爲'target_hours'的表。目標和給定水平 - 字段名稱(L1,L2,L3,L4,L5)已在表格中以小時分配並提及,如下所示。在mysql表中選擇列名

|L1 | L2 | L3 | L4 | L5 | 
|---| --- | ---|--- |--- | 
|192| 168 | 144| 120| 96 | 

我只需要得到水平(申請名稱)已由按以下條件使用mysql query在指定時間內完成的具體工作。舉一個例子,讓我們花上X小時。

L5 --> L5 >= x hours 
L4 --> L4 >= x hours > L5 
L3 --> L3 >= x hours > L4 
L2 --> L2 >= x hours > L3 
L1 --> L1 >= x hours > L2 

作爲一個例子,如果特定任務在135小時內完成,查詢應該輸出爲L3。

+1

這類問題是設計不良的症狀。 – Strawberry

回答

0

雖然我做這個是一個設計不良的症狀一致,一個辦法來解決,這將是一堆工會:

select 
    lvl 
from (
    select l1 as lvl from limits 
    union all 
    select l2 from limits 
    union all 
    select l3 from limits 
    union all 
    select l4 from limits 
    union all 
    select l5 from limits 
    order by 
    lvl asc 
) x 
where 
    lvl > 135 
limit 
    0, 1 
0

最好的解決辦法是通過移動你的表結構的正常化各級爲行從列:

level, hours 
L1 , 192 
L2 , 168 
... 

在這種情況下,查詢是:

select * from target_hours where hours>... 
order by hours asc limit 1 

這個解決方案的優點是它很靈活(你可以擁有任意數量的級別),並且查詢可以使用索引。

如果你堅持維護當前的表結構,那麼你可以使用case expression,達到了預期的結果:

select case 
      when L5>=... then L5 
      when L4>=... and ...>L5 then L4    
      when L3>=... and ...>L4 then L3 
      when L2>=... and ...>L3 then L2 
      when L1>=... and ...>L2 then L1 
     end as hours 
from target_hours 

這個解決方案是不靈活的,因爲如果你要檢查多個級別,那麼你必須改變表結構和查詢。另外,它不能使用索引來查找相關值。