常用查询例子

在命令行中,选择要操作的数据庫:

  1. shell> mysql your-database-name

创建数据庫表,并往里添加数据:

  1. CREATE TABLE shop (
  2. article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
  3. dealer CHAR(20) DEFAULT '' NOT NULL,
  4. price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
  5. PRIMARY KEY(article, dealer));
  6. INSERT INTO shop VALUES
  7. (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
  8. (3,'C',1.69),(3,'D',1.25),(4,'D',19.95);

上述语句执行后,有如下结果:

  1. mysql> select * from shop;
  2. +---------+--------+-------+
  3. | article | dealer | price |
  4. +---------+--------+-------+
  5. | 0001 | A | 3.45 |
  6. | 0001 | B | 3.99 |
  7. | 0002 | A | 10.99 |
  8. | 0003 | B | 1.45 |
  9. | 0003 | C | 1.69 |
  10. | 0003 | D | 1.25 |
  11. | 0004 | D | 19.95 |
  12. +---------+--------+-------+
  13. 7 rows in set (0.01 sec)

查询列特定列中的最大值

  1. SELECT MAX(article) AS article FROM shop;
  2. +---------+
  3. | article |
  4. +---------+
  5. | 4 |
  6. +---------+

简单的子查询:

  1. SELECT article, dealer, price
  2. FROM shop
  3. WHERE price=(SELECT MAX(price) FROM shop);
  4. +---------+--------+-------+
  5. | article | dealer | price |
  6. +---------+--------+-------+
  7. | 0004 | D | 19.95 |
  8. +---------+--------+-------+

也可以通过以下方式来达到同样的效果:

  1. SELECT s1.article, s1.dealer, s1.price
  2. FROM shop s1
  3. LEFT JOIN shop s2 ON s1.price < s2.price
  4. WHERE s2.article IS NULL;
  5. SELECT article, dealer, price
  6. FROM shop
  7. ORDER BY price DESC
  8. LIMIT 1;

每个分组里的最大值

  1. SELECT article, MAX(price) AS price
  2. FROM shop
  3. GROUP BY article;
  4. +---------+-------+
  5. | article | price |
  6. +---------+-------+
  7. | 0001 | 3.99 |
  8. | 0002 | 10.99 |
  9. | 0003 | 1.69 |
  10. | 0004 | 19.95 |
  11. +---------+-------+

原文: https://strongyoung.gitbooks.io/mysql-reference-manual/content/tutorial/common_queries.html