从MySQL表中查找4列值之间的最低值

时间:2013-05-17 05:23:40

标签: mysql sql

tabl_priceList:

+--------+------+------+------+-------
| ProductID| price1 | price2 | price3 |
+--------+--------+------+------+------
|   10001 |   30    |  56    |   23   |
|   10002 |   650   | 560    |  675   |
|   10003 |   57    |  50    |  60    |
|   10004 |  300    | 305    |  3009  |
+--------+------+------+------+-------

我需要找出每行的最小列值。

看起来像。

-----+------+------+---
| ProductID| smallest | 
+--------+--------+-----
|   10001 |    23     | 
|   10002 |    560    | 
|   10003 |    50     | 
|   10004 |    300    | 
+--------+------+------

请帮我解决问题

2 个答案:

答案 0 :(得分:7)

只需使用LEAST()

SELECT ProductID, LEAST(price1, price2, price3) smallest
FROM   tabl_priceList

输出

╔═══════════╦══════════╗
║ PRODUCTID ║ SMALLEST ║
╠═══════════╬══════════╣
║     10001 ║       23 ║
║     10002 ║      560 ║
║     10003 ║       50 ║
║     10004 ║      300 ║
╚═══════════╩══════════╝

答案 1 :(得分:0)

或者,您也可以使用CASE语句:

SELECT
ProductID
, CASE WHEN price1 <= price2 and price1 <= price3 THEN Price1
       WHEN price2 <= price1 and price2 <= price3 THEN Price2
       ELSE price3 END AS smallest
FROM tabl_priceList;

输出:

╔═══════════╦══════════╗
║ PRODUCTID ║ SMALLEST ║
╠═══════════╬══════════╣
║     10001 ║       23 ║
║     10002 ║      560 ║
║     10003 ║       50 ║
║     10004 ║      300 ║
╚═══════════╩══════════╝

See this SQLFiddle