常用sql语句

来源:互联网 发布:河南网络知识竞赛 编辑:程序博客网 时间:2024/05/22 09:41

一、创建表

create table stu(id integer, name text, addr text, sex text);

设置主键,每个表只能有一个主键,设置为主键的列数据不可以重复。

create table stu(id integer primary key, name text, addr text, sex text);

二、修改表 alter语句

(1)、添加列

alter table stu add score text;

(2)、修改表名

alter table stu rename to terch;

三、删除表 drop table语句

drop table stu;

四、插入新行

(1)全部赋值

insert to stu values (1,‘lucy',‘beijing');(2)部分赋值<pre name="code" class="sql">insert into stu (id,name) values (4,'lucy');

五、修改表中数据 update语句

update stu set id=1, addr = “tianjin” where name='lucy'; 
六、删除表中数据 delete语句
delete from stu where id=6;

七、查询语句 select 基础
select * from stu;select * from stu where id=4;select (id,addr) from stu where name='lucy';

八、匹配条件语法 (提高)
(1)、in 允许我们在where 子句中规定多个值。
select * from stu where id in (5,7,8);(2)、and 可在where 子语句中把两个或多个条件结合起来。
select * from stu where name='lucy' and sex='F';
(3)、or 可在where 子语句中把两个或多个条件结合起来select * from stu where name='lucy' or name='Bob';(4)、between A and B 会选取介于A、B之间的数据范围
select * from stu where id between 1 and 9;select * from stu where name between 'a' and 'k';
(5)、like 用于模糊查找,可以用通配符“%”代表缺少的字符(一个或多个)
select * from stu where id like 4;select * from stu_info where id like '%008%';
(6)、not 可取出原结果集的补集
1、where 列名 not in(列值1, 列值2, ...)
2、where not(列1 = 值1 [and 列2 = 值2 and...])
3、where not(列1 = 值1 [or 列2 = 值2 or...])
4、where 列名 not betweenA andB
5、where 列名 not like 列值
select * from stu where id not in (5,6,7);select * from stu where not (id = 5 and name ="bob");select * from stu where not (id = 5 or name = "bob");select * from stu where id not between 1 and 10;select * from stu where name not like '%ob' 

九、order by 默认为升序,desc为降序
select * from stu order by id;select * from stu order by id desc;

十、常用聚集函数
avg() 返回某列的平均值
count() 返回某列的行数
max() 返回某列的最大值
min() 返回某列的最小值
sum() 返回某列值之和
注:不统计NULL行
select max(score),avg(score),count(score) from persons;select sum(score) from persons where id in(5,6);

十一、数据分组:group by 语句
例如:查询每个班级中的人数、平均分
select id,class,avg(score),count(*) from persons where id=1 group by class;

十二、数据分组,除了能用group by分组数据外,还可以包括哪些分组,排除哪些分组。
例如:查看班级平均分大于90的班级
select class,avg(score),count(*) from persons group by class having avg(score) >= 90;










0 0