查询表内容 表:Student
select * from Student
查询指定列 列:name,sex,age
select name,sex,age from Student
条件查询: where 字句
select name,sex,age from Student where age=20 select name,sex,age from Student where name='张三' select name,sex,age from Student where sex='男'
格式:SELECT 列名 FROM 表名 where 条件
select name,sex,age from Student where age>25 查询大于25的数据 如果name,sex,age 换成*号,那么所有将列出来。
查询所有人数的数量(count 聚合函数)
select count(*) from Student 范围查询: between 字句 select * from Student where id between 10 and 15
-------------------------
操作符 描述
= 等于
<> 不等于
> 大于
< 小于 >= 大于等于
<= 小于等于
BETWEEN 在某个范围内
LIKE 搜索某种模式
模糊查询
百分号代表所有,但是不包括空。 select * from Student where address like '%'; 包含这个词。 select * from Student where address like '%青%'; select * from Student where name like '%付%'; select * from Student where phone like '%133%'; 匹配开头 select * from Student where phone like '133%'; 匹配结尾 select * from Student where phone like '%5'; 匹配开头与结尾 select * from Student where phone like '1%3'; 匹配单个字符: select * from Student where phone like '_33%'; 匹配多个字符: select * from Student where phone like '_[123]3%'; 只要第二位有1到3的数字都会显示,但是第3位要为3 select * from Student where phone like '_[a-b-c-0-9]6%' 可以用"-"来代表连续。 不匹配 select * from Student where phone like '_[!3][6]%'; 只要里面包含的有,就会显示,看你怎么加。
SQL注释
第一种: 单行注释 --select * from Student 第二种: 多行注释 /**/ 第三种:
查询NULL值语句
查询NULL值 select * from Student where phone is null is英文意思为:是 查询非NULL值 select * from Student where phone is not null is not的英文意思是 是;不是null的值
逻辑查询
1.AND select * from Student where name='张三' and sex='女' /* AND 两边都要为真,才会为真 如果有一边为假,那么两边为假。 */ 2.OR select * from Student where name='张三' or sex='女' /* OR 两边如果一边为真的话,一边为假,那么就为真, 如果两边都是假的话,那么就为假。 如果两边都真,还是为真。 */
IN查询
1.or进行查询: select * from Student where id=1 or id=2 or id=4 只有为真,就是真实存在,就会正常查询 2.In查询: select * from Student where id in (1,2,3) 直接查询。不需要用OR这么复杂 3.NOT IN查询: select * from Student where id not in (1,2,3) not in 就是,是;不是id1.2.3的其他都查询。 4.TOP 子句 select top 2 * from Student 查询前两行的数据
order by 语句
1.排序语句 1.ASC(正序排列) select * from Student order by id asc id编号正序排列 select * from Student order by age,id asc age和id正序排列 2.DESC(倒序排列) select * from Student order by id desc id编号倒序排列 select * from Student order by age,id desc age和id倒序排列 3.扩充方法黑阔猜数据库的列 select * from Student order by 1,2,3,4,5,6,7, 查看有没有7列,有的话就回显,没有的话,就报错。安 全人员可以将列改成7 然后7的后面列改成12。
DISTINCT 去重复数据
select DISTINCT age from Student order by 1
插入数据(INSERT)
第一种写法:完整写法 insert into Student (name,sex,age,greadName,phone,address) values('张三','女',20,'一年级','132323232','青岛'); 声明:写多一点,就不会报错,对插入格式严谨。 虽然比较复杂。 第二种写法:简单写法 insert into Student values('张三','女',20,'一年级','1322334','青岛') 声明:写法简单,用于表结构比较简单,如果数据排序乱了的话,他会不严格的执行,第一种写法,插入数据时比较严格。
本文作者为lufei,转载请注明。