SQL基础语法

一.查询语法

1.全表查询

select * from table_name;
#显示整个表中所有的数据

2.选择查询

select 列名 from table_name;
#显示(查询)多个列,每个列之间用“ , ”隔开
#在表中选择指定的列进行显示

3.选择查询——赋予临时名

select 列名 as 临时名 from table_name;
#执行后列名显示为临时名

4.查询及运算

select1 *2 as total from table_name;
select 常量 *2 as total from table_name;
#将列间对应行的数据进行运算显示在新的列中

5.条件查询

select1,列2 from table_name where1=?;
#在表中选取where 后限定的行进行显示

6.条件查询——运算符

#常见运算符 = != < > BETWEEN
select1,列2 from table_name where1 !=?

BETWEEN运算符的使用
select1,列2 from table_name where1 between value1 and value2
取出value1与value2之间行的值

7.条件查询——空值

#空值null
#查询有哪些值为空(未填写)
is null
selectfrom table_name where 列名 is null
#查询出“列名”中对应列中数据为空(未填写)的行

#查询有哪些值不为空(未填写)
is not null
selectfrom table_name where 列名 is not null
#查询出“列名”中对应列中数据不为空(未填写)的行

8.条件查询——模糊查询

#like / not like
#常用通配符
	%任意长度的字符序列
	_任意单位个字符
select * from table_name where 列名 like '%a%'
#显示出列名中包含'a'的行
select * from table_name where 列名 like 'a%'
#显示出列名中首字母为'a'的行

select * from table_name where 列名 like '_a_'
#显示出列名中包含'a'的行,并且长度为3个字符
select * from table_name where 列名 like 'a__'
#显示出列名中首个字符为'a'的行,并且长度为3个字符

9.条件查询——逻辑运算

#逻辑运算符
	AND:逻辑与同时满足多个条件才返回true
	OR: 逻辑或有一个条件满足就返回true
	NOT:逻辑非,用于否定一个条件
select * from where 判断条件1 or 判定条件2;

10.基础语法——去重

#使用 DISTINCT 关键字实现去重操作
select distinct1,列2 from table_name

11.基础语法——排序

#关键字 order by
#升序 asc
#降序 desc
select * from table_name order by1 asc,列2 desc;
#先按列一的排序规则进行,若有相同的值则按照列2的规则将相同的排序