一、DQL基础应用
1.select 语句应用
1.1 select 的执行逻辑
shell
select 列1,列2
from 表
where 条件
group by 条件
having 条件
order by 条件
limit 条件
1.2 select 单独使用的情况(MySQL独有)
(1) select @@参数名
SELECT @@datadir;
SELECT @@port;
SELECT @@socket;
SHOW VARIABLES;
SELECT @@innodb_flush_log_at_trx_commit;
1.3 select 函数
SELECT NOW();
SELECT DATABASE();
SELECT USER();
SELECT CONCAT("hello word")
SELECT USER,HOST FROM mysql.`user`
SELECT GROUP_CONCAT(USER,"@",HOST) FROM mysql.user;
2.from 使用
USE world;
SHOW TABLES
SELECT * FROM city
**3.where子句的使用****
`3.1 等值查询`
-- 查询中国城市信息
SELECT * FROM city WHERE countrycode='CHN';
`3.2 不等值查询`
-- 查询人口数量小于100人的
SELECT * FROM city WHERE population<100;
-- 查询ID小于10的城市
SELECT * FROM city WHERE id<10;
-- 查询不是中国的城市信息
SELECT * FROM city WHERE countrycode!='CHN';
`3.3 模糊查询`
-- 查询国家代号为CH打头的城市信息
SELECT * FROM city WHERE countrycode LIKE 'CH%';
SELECT * FROM city WHERE countrycode LIKE '%CH%';
-- 注意: 避免使用 like 中前面带%的模糊查询
`3.4 逻辑连接符 (and,or)`
-- 查询中国城市人口超过500w的城市信息
SELECT * FROM city WHERE countrycode ='CHN' AND population > 5000000;
-- 改城市名字
UPDATE city SET NAME='beijing' WHERE id=1891;
-- 查看山东省或者河北省的城市信息
SELECT * FROM city WHERE district='shandong' OR district='hebei'
-- 查询人口数量在500w-600w的城市
SELECT * FROM city WHERE population>5000000 AND population<6000000;
-- BETWEEN and 区间
SELECT * FROM city WHERE population BETWEEN 1000000 BETWEEN 2000000;
`-- 3.6 where 配合 in 使用`
-- 查看山东和河南的城市信息
SELECT *FROM city WHERE district IN('shandong','henan');
4.group by 子句+聚合函数应用
4.1 什么是分组
按照某个列进行分组 -- 4.2 常用的聚合函数
COUNT() 计数
MAX() 最大值
MIN() 最小值
AVG() 平均值
SUM() 求和
GROUP_CONCAT() 列转行
`4.3例子`
-- 统一每个国家的总人口数
SELECT countrycode,SUM(population) FROM city GROUP BY countrycode;
-- 统计中国每个省的城市个数及省总人口数
SELECT district,COUNT(NAME),SUM(population) FROM city WHERE countrycode='CHN'
GROUP BY district
-- 统计各个国家的城市名列表
SELECT countrycode ,GROUP_CONCAT(NAME)
FROM city
GROUP BY countrycode
5.having 语句(后过滤)
-- 统计中国每个省的城市个数及省总人口数
-- 只显示人口总数大于800w的省
SELECT district,COUNT(NAME),SUM(population)
FROM city
WHERE countrycode='CHN'
GROUP BY district
HAVING SUM(population)>8000000;
6.order by 子句
-- 以上例子将人口数进行排序输出
SELECT district,COUNT(NAME),SUM(population)
FROM city
WHERE countrycode='CHN'
GROUP BY district
HAVING SUM(population)>8000000
ORDER BY SUM(population) DESC;
-- 查询中国所有城市信息,并以人口数降序输出
SELECT * FROM city WHERE countrycode='CHN'
ORDER BY population DESC ;
7.limit 应用
SELECT * FROM city WHERE countrycode='CHN'
ORDER BY population DESC
LIMIT 5 OFFSET 5;
SELECT * FROM city WHERE countrycode='CHN'
ORDER BY population DESC
LIMIT 3,5;
-- 跳过前N行,显示M行(N和M代表的是数字)
LIMIT M offet N
LIMIT N,M
8.distinct 应用
-- 查询所有的国家代号信息
SELECT DISTINCT countrycode FROM city;
**9.untion与untion all****
网友评论