mysql MIN和MAX函数用if语句

时间:2012-06-13 23:20:45

标签: mysql

我有一个像这样的SQL查询:

SELECT IF( (SELECT COUNT(*) FROM `test_table2` WHERE `id` = t.`id`) > 0,
    (t.`price` + (SELECT `price` FROM `attribute` WHERE `id` = t.`id` LIMIT 1)),
    t.`price`
) AS `full_price`, 
MIN(`full_price`) as `min`, MAX(`full_price`) as `max` 
FROM `test_table` t

如何在不使用if语句中的重复代码的情况下检索最小值和最大值?

感谢。

1 个答案:

答案 0 :(得分:2)

full_price的计算括在子查询中:

SELECT 
      MIN(full_price) AS min_full
    , MAX(full_price) AS max_full
FROM
  ( SELECT IF( (SELECT COUNT(*) FROM test_table2 WHERE id = t.id) > 0
             , t.price + (SELECT price FROM attribute WHERE id = t.id LIMIT 1)
             , t.price
             ) AS full_price  
    FROM test_table AS t
    WHERE ...                 --- if you want conditions applied to `test_table`
                              --- before calculating the `full_price`
  ) AS tmp ;

改进:

  • (标准SQL):使用CASE子句,而不是仅用于MySQL的IF
  • (效果):将(SELECT COUNT ...) > 0更改为EXISTS (SELECT ... )。它通常更快。

您的查询将变为:

SELECT 
      MIN(full_price) AS min_full
    , MAX(full_price) AS max_full
FROM
  ( SELECT 
        CASE WHEN 
               EXISTS (SELECT * FROM test_table2 WHERE id = t.id) 
             THEN t.price + (SELECT price FROM attribute WHERE id = t.id LIMIT 1)
             ELSE t.price
        END AS full_price  
    FROM test_table AS t
    WHERE ... 
  ) AS tmp ;