数据库优化第3讲 - 数据库的查询

一、数据库的查询

1.1 MySQL查询

select基础语法
	select * from 表名字;
select完整语法
	select 去重选项 字段列表 [as 字段别名] from 数据源 [where子句] [group by 子句] [having子句] [order by 子句] [limit子句];

1.2 查询

	-- 查询所有字段
	-- select * from 表名;
	select * from students;

	-- 查询指定字段
	-- select 列1,列2,... from 表名;
	select name,age,gender from students;
	
	-- 使用 as 给字段起别名
	-- select 字段 as 名字.... from 表名;
	select name as 姓名,age,gender from students;

	-- select 表名.字段 .... from 表名;
	select name as 姓名,age,gender from students as s;
	
	-- 可以通过 as 给表起别名
	-- select 别名.字段 .... from 表名 as 别名;
	select distinct name,age from students as s;
	
	-- 消除重复行
	-- distinct 字段
	select distinct name,age from students;

1.3 条件查询

1.3.1 比较运算符

-- 比较运算符
		-- select .... from 表名 where .....
		-- >
		-- 查询 大于18岁 的信息
		select * from students where age > 18;

		-- <
		-- 查询小于18岁的信息
		select * from students where age < 18;

		-- >=
		-- <=
		-- 查询小于或者等于18岁的信息
		select * from students where age <= 18;
		-- =
		-- 查询年龄为18岁的所有学生的名字
		select * from students where age = 18;

		-- != 或者 <>  不等于 
		-- 查询姓名不是居然的
		select * from students where name != '居然';

1.3.2 逻辑运算符

MySQL数据库中优先级:not>and>or

-- and
		-- 18到28之间的所有学生信息
		select * from students where age >18 and age < 28;
		-- select * from students where 18 < age < 28;  错误的写法
		-- select * from students where age >18 and  < 28;


		-- 18岁以上的女性
		select * from students where age > 18 and gender='女';

		-- or
		-- 查询编号小于4或没被删除的学生
		select * from students where id < 4 or is_delete = 0;

		-- not 取反
		-- 查询年龄不是18岁的   女性 这个范围内的信息
		select * from students where not (age = 18 and gender = '女'); -- 可读性 更高
		select * from students where age != 18 and gender = '女';

		-- 年龄不是小于或者等于18 并且是女性
		select * from students where (not age <= 18)  and gender = 2;

		-- select * from students where age > 18  and gender = 2;
		

1.3.3 模糊查询

		-- like 
		-- % 替换任意多个
		-- _ 替换1个

		-- 查询姓名中 以 "小" 开始的名字 
		select * from students where name like '小%';  -- '小于' '小张' '小xx' 

		-- 查询姓名中 有 "小" 所有的名字
		select * from students where name like '%小%';		-- '小于' '小张' '小xx' 'x小x'

		-- 查询有2个字的名字
		select * from students where name like '__';		-- xx  xx

		-- 查询至少有2个字的名字
		select * from students where name like '__%';

		-- rlike 正则
		-- 查询以 周开始的姓名
		select name from students where name rlike "^周.*";

		-- 查询以 周开始、伦结尾的姓名
		select name from students where name rlike "^周.*伦$";

1.3.4 空判断

-- 判空is null  不能用 = 
-- 查询身高为空的信息
select * from students where name is null;

-- 判非空is not null
select * from students where name is not null;
发布了46 篇原创文章 · 获赞 4 · 访问量 1303

猜你喜欢

转载自blog.csdn.net/Yauger/article/details/103388028