Home Database Mysql Tutorial MySQL常用查询的例子

MySQL常用查询的例子

Jun 07, 2016 pm 04:04 PM
mysql under example study Commonly used Inquire

下面是一些学习如何用MySQL解决一些常见问题的例子。一些例子使用数据库表“shop”,包含某个商人的每篇文章(物品号)的价格。假定每个商人的每篇文章有一个单独的固定价格,那么(物品,商人)是记录的主键。 你能这样创建例子数据库表: CREATE TABLE shop ( a

下面是一些学习如何用MySQL解决一些常见问题的例子。一些例子使用数据库表“shop”,包含某个商人的每篇文章(物品号)的价格。假定每个商人的每篇文章有一个单独的固定价格,那么(物品,商人)是记录的主键。
你能这样创建例子数据库表:
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.1 列的最大值
“最大的物品号是什么?”
SELECT MAX(article) AS article FROM shop
+---------+
| article |
+---------+
|  4 |
+---------+
3.2 拥有某个列的最大值的行
“找出最贵的文章的编号、商人和价格”
在ANSI-SQL中这很容易用一个子查询做到:
SELECT article, dealer, price
FROM  shop
WHERE price=(SELECT MAX(price) FROM shop)
在MySQL中(还没有子查询)就用2步做到:
用一个SELECT语句从表中得到最大值。
使用该值编出实际的查询:
SELECT article, dealer, price
FROM  shop
WHERE price=19.95
另一个解决方案是按价格降序排序所有行并用MySQL特定LIMIT子句只得到的第一行:
SELECT article, dealer, price
FROM  shop
ORDER BY price DESC
LIMIT 1
注意:如果有多个最贵的文章( 例如每个19.95),LIMIT解决方案仅仅显示他们之一!
3.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.4 拥有某个字段的组间最大值的行
“对每篇文章,找出有最贵的价格的交易者。”
在ANSI SQL中,我可以用这样一个子查询做到:
SELECT article, dealer, price
FROM  shop s1
WHERE price=(SELECT MAX(s2.price)
 FROM shop s2
 WHERE s1.article = s2.article)
在MySQL中,最好是分几步做到:
得到一个表(文章,maxprice)。见3.4 拥有某个域的组间最大值的行。
对每篇文章,得到对应于存储最大价格的行。
这可以很容易用一个临时表做到:
CREATE TEMPORARY TABLE tmp (
article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
price  DOUBLE(16,2) DEFAULT '0.00' NOT NULL);
LOCK TABLES article read;
INSERT INTO tmp SELECT article, MAX(price) FROM shop GROUP BY article;
SELECT article, dealer, price FROM shop, tmp
WHERE shop.article=tmp.articel AND shop.price=tmp.price;
UNLOCK TABLES;
DROP TABLE tmp;
如果你不使用一个TEMPORARY表,你也必须锁定“tmp”表。
“它能一个单个查询做到吗?”
是的,但是只有使用我称之为“MAX-CONCAT诡计”的一个相当低效的诡计:
SELECT article,
  SUBSTRING( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer,
 0.00+LEFT( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS price
FROM  shop
GROUP BY article;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|0001 | B | 3.99 |
|0002 | A | 10.99 |
|0003 | C | 1.69 |
|0004 | D | 19.95 |
+---------+--------+-------+
最后例子当然能通过在客户程序中分割连结的列使它更有效一点。
3.5 使用外键
不需要外键联结2个表。
MySQL唯一不做的事情是CHECK以保证你使用的键确实在你正在引用表中存在,并且它不自动从有一个外键定义的表中删除行。如果你象平常那样使用你的键值,它将工作得很好!
CREATE TABLE persons (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR(60) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE shirts (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
owner SMALLINT UNSIGNED NOT NULL REFERENCES persons,
PRIMARY KEY (id)
);
INSERT INTO persons VALUES (NULL, 'Antonio Paz');
INSERT INTO shirts VALUES
(NULL, 'polo', 'blue', LAST_INSERT_ID()),
(NULL, 'dress', 'white', LAST_INSERT_ID()),
(NULL, 't-shirt', 'blue', LAST_INSERT_ID());
INSERT INTO persons VALUES (NULL, 'Lilliana Angelovska');
INSERT INTO shirts VALUES
(NULL, 'dress', 'orange', LAST_INSERT_ID()),
(NULL, 'polo', 'red', LAST_INSERT_ID()),
(NULL, 'dress', 'blue', LAST_INSERT_ID()),
(NULL, 't-shirt', 'white', LAST_INSERT_ID());
SELECT * FROM persons;
+----+---------------------+
| id | name|
+----+---------------------+
| 1 | Antonio Paz |
| 2 | Lilliana Angelovska |
+----+---------------------+
SELECT * FROM shirts;
+----+---------+--------+-------+
| id | style  | color | owner |
+----+---------+--------+-------+
| 1 | polo| blue  | 1 |
| 2 | dress  | white | 1 |
| 3 | t-shirt | blue  | 1 |
| 4 | dress  | orange | 2 |
| 5 | polo| red| 2 |
| 6 | dress  | blue  | 2 |
| 7 | t-shirt | white | 2 |
+----+---------+--------+-------+
SELECT s.* FROM persons p, shirts s
WHERE p.name LIKE 'Lilliana%'
  AND s.owner = p.id
  AND s.color 'white';
+----+-------+--------+-------+
| id | style | color | owner |
+----+-------+--------+-------+
| 4 | dress | orange | 2 |
| 5 | polo | red| 2 |
| 6 | dress | blue  | 2 |
+----+-------+--------+-------+
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

See all articles