根据sql语句中的其他字段选择正确的字段

时间:2013-02-01 18:26:19

标签: php mysql sql

我正在寻找一个解决方案,我可以直接在我的sql语句中根据字段值获取结果。

例如,如果我有以下结构:

calculated_result     result_one     result_two     result_three
1                     2.50           3.40           2.90
2                     1.90           2.00           3.90
1                     1.30           2.23           1.50

然后我想进行搜索,它应返回所有结果,其中calculate_result为1且result_one高于2.30且小于或等于2.65。

问题是,我不知道如何只返回适合用户搜索的行。

calculated_result = 1应检查result_one是否大于行内容 calculated_result = 2应检查result_two是否大于行内容 等

希望它有意义。

4 个答案:

答案 0 :(得分:4)

select  *
from    myTable
where   (calculated_result = 1 and result_one between 2.30 and 2.650)
or      (calculated_result = 2 and result_two between 2.30 and 2.650)
or      (calculated_result = 3 and result_three between 2.30 and 2.650)

或者,如果您想使用case

select  *
from    myTable
where   case 
          when calculated_result = 1 then result_one 
          when calculated_result = 2 then result_two
          when calculated_result = 3 then result_three
        end between 2.30 and 2.650

答案 1 :(得分:1)

您可以尝试使用CASE operator

SELECT * FROM yourTable
WHERE (CASE
  WHEN calculated_result = 1 THEN result_one
  WHEN calculated_result = 2 THEN result_two
END) > 2.3
AND (CASE
  WHEN calculated_result = 1 THEN result_one
  WHEN calculated_result = 2 THEN result_two
END) <= 2.65

答案 2 :(得分:0)

试试这个

SELECT 
       * 
FROM 
       table_name 
WHERE 
       calculated_result = 1 AND
       result_one > 2.30 AND
       result_one <= 2.65 

答案 3 :(得分:0)

另:

select  *
from    myTable
where   calculated_result in (1, 2, 3) and 
(result_one between 2.30 and 2.650 or result_two between 2.30 and 2.650
or result_three between 2.30 and 2.650)
;

DEMO