3.6 Examples of Common Queries常见查询示例

3.6.1 The Maximum Value for a Column列的最大值
3.6.2 The Row Holding the Maximum of a Certain Column包含某一列的最大值的行
3.6.3 Maximum of Column per Group每个组的最大列数
3.6.4 The Rows Holding the Group-wise Maximum of a Certain Column包含某一列按组最大值的行
3.6.5 Using User-Defined Variables使用用户定义的变量
3.6.6 Using Foreign Keys使用外键
3.6.7 Searching on Two Keys搜索两个键
3.6.8 Calculating Visits Per Day计算每天的访问量
3.6.9 Using 使用AUTO_INCREMENT

Here are examples of how to solve some common problems with MySQL.下面是如何使用MySQL解决一些常见问题的示例。

Some of the examples use the table shop to hold the price of each article (item number) for certain traders (dealers). 一些示例使用表格shop为某些贸易商(经销商)保存每件商品(项目编号)的价格。Supposing that each trader has a single fixed price per article, then (article, dealer) is a primary key for the records.假设每个交易者每件商品都有一个固定的价格,那么(商品,经销商)是记录的主键。

Start the command-line tool mysql and select a database:启动命令行工具mysql并选择一个数据库:

shell> mysql your-database-name

To create and populate the example table, use these statements:要创建和填充示例表,请使用以下语句:

CREATE TABLE shop (
    article INT UNSIGNED  DEFAULT '0000' NOT NULL,
    dealer  CHAR(20)      DEFAULT ''     NOT NULL,
    price   DECIMAL(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);

After issuing the statements, the table should have the following contents:发布报表后,该表应包含以下内容:

SELECT * FROM shop ORDER BY article;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       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 |
+---------+--------+-------+
3.6.1 The Maximum Value for a Column
3.6.2 The Row Holding the Maximum of a Certain Column
3.6.3 Maximum of Column per Group
3.6.4 The Rows Holding the Group-wise Maximum of a Certain Column
3.6.5 Using User-Defined Variables
3.6.6 Using Foreign Keys
3.6.7 Searching on Two Keys
3.6.8 Calculating Visits Per Day
3.6.9 Using AUTO_INCREMENT