MySQL-SQL基本查询

2019-05-28  本文已影响0人  遇明不散

SQL查询

执行顺序
// 以下均已此表为示例 sanguo
/*
+------+-----------+--------+--------+------+---------+
| id   | name      | gongji | fangyu | sex  | country |
+------+-----------+--------+--------+------+---------+
|    1 | 诸葛亮    |    120 |     20 | 男   | 蜀国    |
|    2 | 司马懿    |    119 |     25 | 男   | 魏国    |
|    3 | 关羽      |    188 |     60 | 男   | 蜀国    |
|    4 | 赵云      |    200 |     55 | 男   | 魏国    |
|    5 | 孙权      |    110 |     20 | 男   | 吴国    |
|    6 | 貂蝉      |    666 |     10 | 女   | 魏国    |
|    7 | NULL      |   1000 |     99 | 男   | 蜀国    |
|    8 |           |   1005 |     88 | 女   | 蜀国    |
+------+-----------+--------+--------+------+---------+
*/
order by
# 将英雄按防御值从高到低排序
select * from sanguo order by fangyu desc;
# 将蜀国英雄按攻击值从高到低排序
select * from sanguo where country = "蜀国" order by gongji desc;
# 将魏蜀两国英雄中名字为三个字的按防御值升序排列
select * from sanguo where 
country in("魏国","蜀国") and 
name like "___" order by fangyu asc;
limit
# 在蜀国英雄中,查找防御值倒数第二名至倒数第四名的英雄的记录
select * from sanguo where country = "蜀国" order by fangyu asc limit 1,3;
# 在蜀国英雄中,查找攻击值前3名且名字不为 NULL 的英雄的姓名、攻击值和国家
select * from sanguo where country = "蜀国" and 
name is not null order by gongji desc limit 3;
group by
# 查询表中一共有几个国家
select country from sanguo group by country;
# 计算每个国家的平均攻击力
select country,avg(gongji) from sanguo group by country;
# 查找所有国家中英雄数量最多的前2名的国家名称和英雄数量
# 先分组,再聚,再排序
select country,count(id) as number from sanguo 
group by country order by number desc limit 2;
having
# 找出平均攻击力>105的国家的前2名,显示国家名和平均攻击力
select country,avg(gongji) as avggj from sanguo 
group by country having avggj > 105 order by avggj desc limit 2;
distinct
# 表中都有哪些国家
select distinct country from sanguo;
# 计算蜀国一共有多少个英雄
select count(distinct id) from sanguo where country = "蜀国";
查询表记录时做数学运算
# 查询时所有英雄攻击力翻倍
select id,name,gongji*2 from sanguo;

聚合函数

# 攻击力最强值是多少
select max(gongji) from sanguo;
# 统计id,name 两个字段分别有几条记录
select count(id),count(name) from sanguo;
# 计算蜀国英雄的总攻击力
select sum(gongji) from sanguo where country = "蜀国";
# 统计蜀国英雄中攻击值大于200的英雄的数量
select count(*) from sanguo where country = "蜀国" and gongji > 200;
上一篇下一篇

猜你喜欢

热点阅读