2017-08-18 47 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 

这个解决方案是不灵活的,因为如果你要检查多个级别,那么你必须改变表结构和查询。另外,它不能使用索引来查找相关值。