2012-06-13 64 views
0

我有一個SQL查詢是這樣的:MySQL的MIN和MAX函數與if語句

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語句中使用重複的代碼最大值?

謝謝。

回答

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子句和不IF這是隻限於MySQL。
  • (performance):將(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 ; 
+0

問題解決了,感謝ü。 – uint