這裡有一些用MySQL解決常用問題的例子.
在一些例子中,使用shop表存儲某個商人(經銷商)的每件物品(物品號)的價格。假定每個商人對每項物品有一個固定價格,那麼(article,dealer)即為該記錄的主關鍵字。
啟動命令行工具mysql並選擇數據庫:
shell> mysql your-database-name
(在大多數MySQL中,你可以使用test數據庫)。
你可以使用以下語句創建示例表:
CREATE TABLE shop (
article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
dealer CHAR(20) DEFAULT '' NOT NULL,
price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
PRIMARY KEY(article, dealer));
INSERT INTO shop VALUES
(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
(3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
執行語句後,表應包含以下內容:
SELECT * FROM shop;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0001 | A | 3.45 |
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | B | 1.45 |
| 0003 | C | 1.69 |
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+
3.6.1 列的最大值
“最大的物品號是多少?”
SELECT MAX(article) AS article FROM shop;
+---------+
| article |
+---------+
| 4 |
+---------+
3.6.2 擁有某列最大值的行
任務:找出最貴商品的編號,經銷商和價格
用一個子查詢很容易做到:
SELECT article, dealer, price
FROM shop
WHERE price=(SELECT MAX(price) FROM shop);
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0004 | D | 19.95 |
+---------+--------+-------+
另一個解決方案是使用LEFT JOIN或者按照價格降序排序所有行,然後使用MySQL特定的LIMIT子句只取第一行:
SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.price < s2.price
WHERE s2.article IS NULL;
SELECT article, dealer, price
FROM shop
ORDER BY price DESC
LIMIT 1;
注意:如果有多個最貴的物品,假設每個都是19.95,那麼LIMIT只會取其中的一個.
3.6.3 按組找出列的最大值
任務:找出每項物品的最高價格.
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article;
+---------+-------+
| article | price |
+---------+-------+
| 0001 | 3.99 |
| 0002 | 10.99 |
| 0003 | 1.69 |
| 0004 | 19.95 |
+---------+-------+
3.6.4 擁有某個字段的組間最大值的行
任務:對每項物品,找出最貴價格的經銷商.
這個問題可用這樣一個子查詢來解決:
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | C | 1.69 |
| 0004 | D | 19.95 |
+---------+--------+-------+
上面的例子使用了一個相互關聯的子查詢,這種效率比較低(查看 Section 13.2.10.7,“Correlated Subqueries” ). 其他可能的解決方案在From子句中使用了一個不相關的子查詢或LEFT JOIN.
不相關的子查詢:
SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article) AS s2
ON s1.article = s2.article AND s1.price = s2.price;
LEFT JOIN:
SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL;
LEFT JOIN是基於s1.price達到最大值有效的,那時s2.price不會有更大的值並且s2那一行將為NULL. 查看 Section 13.2.9.2, “JOIN
Syntax”.
3.6.5 使用自定義變量