在mysql表中选择列名

时间:2017-08-18 09:44:16

标签: mysql

嗨我有一个名为'target_hours'的表。目标和给定水平 -  字段名称(L1,L2,L3,L4,L5)在下表中按小时分配和提及如下。

mysql query

我只需要通过以下条件使用L5 --> L5 >= x hours L4 --> L4 >= x hours > L5 L3 --> L3 >= x hours > L4 L2 --> L2 >= x hours > L3 L1 --> L1 >= x hours > L2 获取在特定时间内完成的特定工作的级别(归档名称)。举个例子,我们可以花X小时。

command = "su - user; cd $CONFIG; grep domain domains.xml"

作为示例,如果特定任务在135小时内完成,则查询应输出为L3。

2 个答案:

答案 0 :(得分: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

答案 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

此解决方案不灵活,因为如果您必须检查更多级别,则必须同时更改表结构和查询。此外,它无法使用索引来查找相关值。