mysql10 select语句详解

知识点:
。select基本语法
。数学符号条件
。AND OR IN
。通配符
。排序
。SQL内置函数和计算
。子查询与连接查询

 

 

 

 

 

 

 

 

 

 

下载github的资源

git clone https://github.com/shiyanlou/SQL4.git

在msyql中加载数据(数据库名必须不存在,否则修改或删掉)

source /home/shiyanlou/Desktop/SQL4/MySQL-04-01.sql;

向数据库插入数据

source /home/shiyanlou/Desktop/SQL4/MySQL-04-02.sql;

select 要查询的列名 from 表名 where 限制条件
1、查表中所有数据
select * from employee;
2、查指定的列的所有数据
select name,age from employee; 
3、数学符号条件,用(=,<,>,>=,<=)
select name,age from employee where age>25;    
4、用表中数据当条件
select name,age,phone from employee where name='Mary';
5、and 和or

select * from employee where age>25 and age<30;
6、in "在"  和 not in "不在"
select * from employee where in_dpt not in ('dpt1','dpt3');
7、通配符  

用于实现模糊查询,常用于搜索功能中。

和like联用通配符代表未知字符_代表一个未知字符,%代表不定个未知字符。

select * from employee where phone like '1101__';#用_代表忘记的字符
select * from employee where phone like '1101%';#用%匹配所有
8、对结果排序

oder by  asc升序 ,oder by desc降序。

select * from employee order by salary desc;#注意:排序时不加where
9、内置函数和计算
函数名 count sum avg max min
作用: 计数 求和 求平均值 最大值 最小值

 

 

 

count用于任何数据类型(因为它只是计数)。

sum/avg只能对数据类型做计算。

max和min可用于数值、字符串、或者日期数据类型。

使用as可以给值重命名

select max(salary) as max_salary,min(salary) as min_salary from employee;
9、子查询
SELECT of_dpt,COUNT(proj_name) AS count_project FROM project GROUP BY of_dpt
HAVING of_dpt IN
(SELECT in_dpt FROM employee WHERE name='Tom');

上面代码包含两个 SELECT 语句,第二个 SELECT 语句将返回一个集合的数据形式,

然后被第一个 SELECT 语句用 in 进行判断。

HAVING 关键字可以的作用和 WHERE 是一样的,都是说明接下来要进行条件筛选操作。

区别在于 HAVING 用于对分组后的数据进行筛选

10、连接查询
连接的基本思想是把两个或多个表当作一个新的表来操作。用到(join)
SELECT id,name,people_num
FROM employee,department
WHERE employee.in_dpt = department.dpt_name
ORDER BY id;

另一个连接语句格式是使用 JOIN ON 语法,刚才的语句等同于:

SELECT id,name,people_num
FROM employee JOIN department
ON employee.in_dpt = department.dpt_name
ORDER BY id;

练习:未解决啊

mysql> SELECT name, people_num, COUNT(proj_name) AS count_project
    -> FROM employee, department, project
    -> WHERE in_dpt = dpt_name AND of_dpt = dpt_name
    -> GROUP BY name, people_num;
+------+------------+---------------+
| name | people_num | count_project |
+------+------------+---------------+
| Jack |         12 |             2 |
| Mary |         12 |             2 |
| Jim  |         11 |             1 |
| Alex |         11 |             1 |
| Tom  |         15 |             2 |
| Rose |         10 |             1 |
+------+------------+---------------+
6 rows in set (0.00 sec)

前两行不必说了,从三张表选择三列数据;第三行设置三列数据的关系,dpt_name 是唯一值,of_dpt 和 in_dpt 的值必取自 dpt_name 这列,它们应该有外键关系,但不是必须的;第四行分组,分组不可或缺,否则会出现无意义的数据(一般来说连接查询语句中有 COUNT 就会有 GROUP BY),报一个 sql_mode 引起的错误,至于为什么选择 name 和 people_num 分组,大家可以试一下同时去掉 COUNT 和 GROUP BY 语句,看看其中的差异即可理解。

posted @ 2020-06-14 18:06  胜难  阅读(363)  评论(0)    收藏  举报