1. 数据库选择
show databases; |
显示所有数据库 |
create database abc; |
创建数据库abc |
use abc; |
使用数据库abc |
2. 表操作
create table aa(id int , name varchar(30),age int); |
创建表aa id,name,age |
desc aa; |
显示表aa中的字段名 |
drop table aa; |
删除表aa |
3. 插入
insert into aa values(1,'n1',11); |
向表aa中插入一条数据 |
insert into aa(id) values(4); |
向表aa中插入一条数据 |
4. 删除
delete from aa where id=4 and name="n1"; |
删除表aa中所有id为4的数据 |
truncate table aa; |
清空表aa中所有数据,比delete from aa;效率高。 delete不释放空间,truncate会彻底释放空间 |
5. 修改
update aa set age=55,name="xx" where id=1; |
修改表aa中的字段 |
6. 查找
select * from aa; |
选择aa中所有数据 |
|
select name from aa; |
选择aa中所有name数据 |
|
select name,age from aa; |
选择aa中所有name和age数据 |
|
条件查询 |
||
select * from aa where id=1; |
选择aa中所有id为1的数据 |
|
select min(id),name,age from aa where id>=5; |
选择aa中id>=5的数据中id最小的数据 |
|
select * from aa where id between 5 and 30; |
查找id在[5,30]范围内的数据 |
|
select * from aa where id in(5,10,15); |
查找id为括号内列举值的数据 |
|
select distinct name from aa; |
name字段相同时排除 |
|
select * from aa order by id desc; |
查找的数据按照id从大到小排序(不写desc默认从小到大) 排序时,null作为最大值 |
|
select * from aa where name like ‘+%+’; |
查找所有name以+开头,+结尾的字段【%任意数量字符,_单个字符】 |
|
子查询 |
||
select name,age from (select * from aa where id>15) as temp; |
as temp作为()内查询结果的别名,虽然没有被使用但是必须 |
|
多表查询 |
||
select aa.id,name from aa,cc where aa.id=bb.id; sql99写法: select aa.id name from aa inner join cc on aa.id=cc.id; |
从aa和bb两张表中进行查询,限制条件为两个表的id相同 (显示字段 时,如果该字段两个表都有,需要用aa.id这种语法区分) |
|
select aa.id name from aa left outer join cc on aa.id=bb.id; |
在满足aa.id=cc.id情况下,将aa里的数据全部也取出来 |
|
select aa.id name from aa right outer join ccon aa.id=cc.id; |
在满足aa.id=cc.id情况下,将cc里的数据全部也取出来 |
|
select id from aa union select id from cc; |
将两个表的查询结果合并起来 |