本文章來給各位同學介紹一下關於MySQL常用查詢語句介紹,包括有列最大值、擁有某個列的最大值的行、使用用戶變量等等語句。
示例數據庫:
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);
mysql> 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 |
+---------+--------+-------+
1. 列最大值
最大的物品號是什麼?
SELECT MAX(article) FROM shop;
2. 擁有某個列的最大值的行
找出最貴物品的編號、銷售商和價格?
SELECT article, dealer, price FROM shop WHERE price=(SELECT MAX(price) FROM shop);另一個解決方案是按價格降序排序所有行並用MySQL特定LIMIT子句只得到第一行:
SELECT article, dealer, price FROM shop ORDER BY price DESC LIMIT 1;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 |
+---------+-------+
4. 擁有某個字段的組間最大值的行對每項物品,找出最貴價格的物品的經銷商?SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);
5. 使用用戶變量找出價格最高或最低的物品的?
mysql> SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
mysql> SELECT * FROM shop WHERE price=@min_price OR price=@max_price;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+
6. 根據兩個鍵搜索尋找兩個通過OR組合到一起的關鍵字:
SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1' OR field2_index = '1'
還可以使用UNION將兩個單獨的SELECT語句的輸出合成到一起:
SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1'UNIONSELECT field1_index, field2_index FROM test_table WHERE field2_index = '1';