简体   繁体   English

SQL:根据表中的值动态选择列名

[英]SQL: choose a column name dynamically based on its value from the table

I a have a table name(weight) in database我在数据库中有一个表名(权重)

id ID 1000 1000 500 500 300 300 100 100 1 1
1 1 60 60 120 120 140 140 180 180 200 200

for 1000 (1kg)time required is 60 1000 (1kg) 所需时间为 60

for 500 (.5kg)time required is 120 and so on 500 (.5kg) 所需时间为 120 以此类推

based on this weight data should be fetched from the table基于此重量数据应从表中获取

If the entered weight by the user is 700 it should fetch the data of 500 which is the less than 700 and return the value 120如果用户输入的重量是 700,它应该获取小于 700 的 500 的数据并返回值 120

so my code must be like所以我的代码必须像

    SELECT (column name)<700 FROM Weight WHERE id=1 

Thanks:)谢谢:)

It will be much easy if you rearrange your data like:如果您重新排列数据,这将非常容易:

id, condition, value
1,  1000       60
1,  500        120
1,  300        140

and the query would be like this:查询将是这样的:

SELECT value FROM table WHERE id=1 AND condition < 700 ORDER BY condition DESC LIMIT 1

Your approach is not efficient to get your desired results.您的方法无法有效地获得您想要的结果。

Update your table:weight with the below one.使用以下表格更新您的表格:重量。

SQL: SQL:

CREATE TABLE `weight` (
  `id` int(11) NOT NULL,
  `weight` int(11) NOT NULL,
  `time` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `weight` (`id`, `weight`, `time`) VALUES
(1, 100, 60),
(2, 500, 120),
(3, 300, 140),
(4, 100, 180),
(5, 1, 200);
ALTER TABLE `weight`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `weight`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
COMMIT;

Add use the following query to get your desired results.添加使用以下查询以获得所需的结果。

SELECT time FROM weight WHERE weight<=700 ORDER BY weight DESC LIMIT 1

You can use case.. when in select clause as follows:您可以在select子句中使用case.. when ,如下所示:

Select case when your_value >= 1000 then column_1000
            when your_value >= 500 then column_500
            when your_value >= 300 then column_300
            when your_value >= 100 then column_100
             Else column_1 
       End as res_
  From your_table t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM