這將顯示所有產品的最高價或最低價:
SELECT Products.*
FROM Products
WHERE Price = (SELECT MAX(Price) FROM Products)
OR Price = (SELECT MIN(Price) FROM Products)
或者,也許你想是這樣的:
SELECT
Products.*,
m.mx As Highest,
m.mn As Lowest,
CASE WHEN Products.Price = m.mx THEN 'Max' ELSE 'Min' END As Is_Max_or_Min
FROM
Products INNER JOIN (
SELECT MAX(Price) mx, MIN(Price) mn
FROM Products
) m ON Products.Price IN (m.mx, m.mn)
如果您希望他們在同一排,如果只有一個產品價格最高,而最低價格只有一個產品,則可以使用如下所示:
SELECT
m.Lowest, p1.Name Name_Lowest,
m.Highest, p2.Name Name_Highest
FROM
(SELECT MIN(Price) Lowest, MAX(Price) Highest FROM Products) m
INNER JOIN Products p1 ON m.Lowest = p1.Price
INNER JOIN Products p2 ON m.Highest = p2.Price
LIMIT 1
或者,如果你只是需要一些easyer,你可以這樣做:
(SELECT 'Max' Is_Max_Or_Min, Products.*
FROM Products ORDER BY Price DESC LIMIT 1)
UNION ALL
(SELECT 'Min', Products.*
FROM Products ORDER BY Price LIMIT 1)
你只是想價格或整排設有此價格是多少?你將如何打破關係(多行共享最低/最高)?挑一個任意一個?返回所有同齡人? –