MySQL Chinese reference manual

Source: Internet
Author: User
Tags manual

Here are some examples of learning how to use MySQL to solve some common problems.

Some examples use the database table "shop", which contains the price of each article (item number) of a businessman. Assuming that each merchant's article has a separate fixed price, then (the item, merchant) is the primary key of the record.

You can create an example database table like this:

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);

OK, here's the example data:

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 |
+---------+--------+-------+

The maximum value of 3.1 columns

"What's the biggest item number?" ”

SELECT MAX(article) AS article FROM shop
+---------+
| article |
+---------+
|    4 |
+---------+

3.2 Rows that have the maximum value of a column

"Find the number, merchant, and price of the most expensive articles."

在ANSI-SQL中这很容易用一个子查询做到:
SELECT article, dealer, price
FROM  shop
WHERE price=(SELECT MAX(price) FROM shop)

In MySQL (and no subqueries), take 2 steps:

Gets the maximum value from the table with a SELECT statement.

Use this value to compile the actual query:

SELECT article, dealer, price
FROM  shop
WHERE price=19.95

Another solution is to sort all rows in descending price order and use the first line of MySQL-specific limit clauses:

SELECT article, dealer, price
FROM  shop
ORDER BY price DESC
LIMIT 1

Note: If there are multiple most expensive articles (such as each 19.95), the limit solution only shows one of them!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.