目录
1、Join on 内连接、左右连接、外连接(UNION)
(1)inner join:如果表中有至少一个匹配,则返回行。
inner join 与 join 是相同的。
SELECT a.name, a.count, b.date
from inner join b
on a.id=b.id
order by a.count ;
(2)left join:即使右表中没有匹配,也从左表返回所有的行。
SELECT a.name, a.count, b.date
from a
left join b
on a.id=b.id
order by a.count desc ;
(3)RIGHT JOIN:即使左表中没有匹配,也从右表返回所有的行。
SELECT a.name, a.count, b.date
from a
right join b
on a.id=b.id
order by a.count desc ;
(4)FULL JOIN:只要其中一个表中存在匹配,则返回行。
MySQL 已经没有全连接了但是实现不了,不过可以换UNION种方式来查询。
(SELECT * from a left join b on a.id=b.id)
UNION
(SELECT * from a right join b on a.id=b.id ) ;
2、Where 的各种运算
(1)条件查询:=、>=、<=、>、<、<>(不等于)。
Select * from table where a = 1; 或者 where a = '1' ;
(2)逻辑运算:
优先级:() > not > and > or
and:与 同时满足条件。
Select * from table where a > 100 and a < 200 ;
or:或 满足其中一个。
Select * from table where a > 100 or a < 200 ;
not:非 不满足这个条件的值。
Select * from table where not a > 100 ;
(3)特殊条件:
is bull:为空。
Select * from table where a is null;
between and:在范围之间,包含边界值。
Select * from table where a between 100 and 200 ;
in:给定等于的值。
Select * from table where a in (100,200,300) ;
like:模糊查询。
%:表示多个值,_下划线表示一个字符单位;
A%:正则表达式,查询以A开头的所有内容;
%A%:查询包含A的所有内容;
%A_:查询倒数第二位为A的所有内容;
Select * from table where a like 'A%' ;
3、order by ASC升序(默认升序) | DESC降序
Select * from a order by a.id,a.name;
先按照 a . id 进行排序,在排序后的基础上再对a.name进行排序。
4、insert into 两种编写形式和select into 的区别
第一种:无需指定插入数据的列名,提供插入的值即可。
insert into table values (value1,value2,value3...);
第二种:提供列名。
insert into table (column1,column2,column3...) values (value1,value2,value3...);
insert into 和 select into 的区别:
insert into table1 select * from table2 where a = 1; //加入一行数据到table1,需要table1必须存在。
select * into table1 from table2 where a = 1; //加入一行数据到table1,table1不存在。
5、update 的语法和注意事项
update table set column1 = value1,column2 = value2 where a = 1;
如果不加where语句,则会更新set列的全部对应数据值。
在Mysql中,可以设置sql_safe_updates = 1;来开启必须加入where语句设置,若不加where,则会报错。
6、delete 语法
delete from table where a = 1; //删除a=1的列。
delete from table; //删除表中所有的数据,但表结构、属性、索引将保持不变。
7、limit 选取指定的条数数据(mysql、sql server 、ms access和oracle各不同)
Mysql 环境:
Select * from table limit 10 ;
Oracle 环境:
Select * from table where rownum <=5 ;
sql server / ms access 环境:
Select top 50 percent * from table ;
8、delete和truncate区别
(1)delete 删除内容但是不释放空间,例如:自动增长的 id 被删除后,新增数据后,id 不连续。
而truncate删除会释放空间,id 增长重新开始。
(2)truncate 删除的速度更快,是数据定义语言(DDL),不会触发事务。而delete 属于数据操作语言DML,操作属于事务,提交之后才会生效,效率慢。
(3)delete 可以使用 where 进行指定列删除,而truncate只能一次性删除全部数据。
(4)执行速度:drop > truncate > delete ;
9、drop 删除语法(mysql、sql server 、ms access和oracle不同之处)
区别:
mysql:
alter table a drop index b ; //删除表 a 的索引 b
db2 / oracle:
drop index b ; //删除索引 b
MS Access:
drop index a.b ; //删除 a 表的索引 b
ms access:
drop index b on a ; //删除 a 表的索引 b
共同之处:
truncate table a ; // 情况表 a
drop table a ; //删除表a
drop database a ; //删除数据库a