MySQL常用查询

建库建表准备环境

create database shop;

use shop;

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

查看表数据

select max(article) as article from shop;

+---------+
| article |
+---------+
|       4 |
+---------+

运用子查询

select article,dealer,price from shop where price = (select max(price) from shop);

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       4 | D      | 19.95 |
+---------+--------+-------+

查询每组的最大值

select article,max(price) as price from shop group by article;

+---------+-------+
| article | price |
+---------+-------+
|       1 |  3.99 |
|       2 | 10.99 |
|       3 |  1.69 |
|       4 | 19.95 |
+---------+-------+

查找最贵的商品所在的行

方法一:

select article,dealer,price from shop where price = (select max(price) from shop);

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       4 | D      | 19.95 |
+---------+--------+-------+

先找出price列中的最大值,在从表中寻找这个最大值所在的行

方法二:

select * from shop order by price desc limit 1;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       4 | D      | 19.95 |
+---------+--------+-------+

将整个shop表降序,取第一行,但这种方法的问题在于,只能取第一行,无法显示所有价值为19.95的商品

可以使用用户自定义的变量来实现同时显示最高价与最低价

select @min_price:=min(price),@max_price:=max(price) from shop;
+------------------------+------------------------+
| @min_price:=min(price) | @max_price:=max(price) |
+------------------------+------------------------+
|                   1.25 |                  19.95 |
+------------------------+------------------------+

mysql> select * from shop where price=@min_price or price=@max_price;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       3 | D      |  1.25 |
|       4 | D      | 19.95 |
+---------+--------+-------+

 

你可能感兴趣的:(MySQL,MySQL)