常用SQL语句实例

DML

常用的

选择:select * from table1 where 范围

插入:insert into table1(field1,field2) values(value1,value2)          

            insert ...  ) select (col3,col4) from yyy   一次插入多条

删除:delete from table1 where 范围

更新:update table1 set field1=value1 where 范围

排序:select * from table1 order by field1,field2 [desc]     如 order by deptno desc, sal 是先按deptno逆序,再按照sal排序

总数:select count * as totalcount from table1     select count(distinct name) from table1

求和:select sum(field1) as sumvalue from table1

平均:select avg(field1) as avgvalue from table1

最大:select max(field1) as maxvalue from table1

最小:select min(field1) as minvalue from table1

Between-and:      select * from table1 where time between time1 and time2

                                     selecta,b,c, from table1 where a not between 数值1 and 数值2

in: select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

exist:  select  。。。 where exist( select * from ...)

分组: select name, sum(sales)  from table group by name  (要确保select 中除了聚合函数的都在group  by 中)

having:对函数产生的值设定条件,在sql语句最后,并不一定和group by 一起出现, 如

         select name ,sum(sales)  from table where name like '%cstnet%'  group by name having sum(sales)>1000

case-when

         select getdate() as 日期,case month(getdate()) when 11 then '十一' else substring('一十',month(getdate()),1) end+'月' as 月份

         SELECT'Number of Titles', Count(*) FROM titles GROUP BY CASE WHEN price IS NULL THEN'Unpriced' ELSE 'Gift to impress relatives' END

         SELECTid,title,(CASE statusWHEN 0 THEN 'open' WHEN 1 THEN 'close' ELSE 'standby'END) AS status FROM your_table

组合查询结果

Union:去重,组合两个结果集;Union all:不去重,组合

Except:去重,A-B; except all 同上  mysql不支持,使用not in

Intersect:去重,交集; intersect all同上  mysql不支持,使用in替代

链接查询:

外连接: 包含表的全部列时

右外连接:包括连接表的匹配行和左表所有行

左外连接:select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a =b.c

子查询:

    在where 或having中插入另一个sql语句,作用是用来连接表格   select * from xxx where col2 [= > < like] (select ...)

日期相关

日期格式:select * from flight where date_format(starttime,'%Y-%m-%d')='1998-01-02'

日期比较:开始结束多于5分钟:datediff(’minute’,开始时间,结束时间)>5 

获取年 getYear(getDate())

授权和取消

grant 权限(sysdba) to 用户名
revoke 权限
(如sysdba) from 用户名; 

更改用户名

alter user 用户名 identified by新密码

DDL

数据库

         create  database `ggg` character set utf8

         drop database ggg

         备份: 导出为sql文件

        包含的约束有 not null     unique    check   主键   外键

         create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)       

         根据已有的表创建新表:

                   A:create table tab_new like tab_old (使用旧表创建新表)

                   B:create table tab_new as select col1,col2… from tab_old definition only

         只复制数据:insert into dust select * from student;//已经创建了新表dust的情况下  忽略auto_increment字段

                                 INSERT INTO yourtable (field1,field2,field3)   SELECT newfield1,newfield2,'fixed value'  FROM yourtable2

         droptable ‘xxx’;           truncate table xxx

         增加一列: alter table xxx add column coltype      add  foreign key(custome_id) references customer(SID)

         删除一列: alter table xxx drop 列名

         修改列名: alter table xxx change address addr char(50)      ALTER TABLE your_tableAUTO_INCREMENT = 2  (插入记录自动增2)

         修改列属性: alter table xxx modify Address  char(30)

         添加主键: alter table xxx add primary key(col)  add primary key(SID) 

         删除主键: alter table xxx drop primary key(col)

级联

CREATE TABLE `roottb` (

  `id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,

  `data` VARCHAR(100) NOT NULL DEFAULT '',

  PRIMARY KEY (`id`)

) TYPE=InnoDB;



CREATE TABLE `subtb` (

  `id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,

  `rootid` INT(11) UNSIGNED NOT NULL DEFAULT '0',

  `data` VARCHAR(100) NOT NULL DEFAULT '',

  PRIMARY KEY (`id`),

  INDEX (`rootid`),

  FOREIGN KEY (`rootid`) REFERENCES roottb(`id`) ON DELETE CASCADE

) TYPE=InnoDB;

    mysql中只有 InnoDB才有外键

索引

         创建聚集索引create clustered index clindx_name  on xxx(列)

         创建非聚集索引create nonclustered index unclindx_name  on xxx(col)

         查看索引统计dbcc show_statistics(roysched,titleidind)

         --更新索引统计update statistics authors

         --重建索引dbcc dbreindex('roysched',unclindx_titleid)

         --删除索引drop index clindx_name

视图

         创建视图:create view viewname as select statement

         删除视图:drop view viewname

存储过程

    create procedureinsert_Student (_name varchar(50),_age int ,out_id int)

begin

       insert intostudentvalue(null,_name,_age);

       select max(stuId)into _id fromstudent;

end;

 

call insert_Student('wfz',23,@id);

select @id;

触发器

 create trigger update_Student BEFORE update on student FOR EACH ROW

创建插入、修改触发器

createtrigger temptrigger_modify

ontemptrigger

forinsert,update

as

begin

  if (select temp_age from inserted) > 15

    begin

      rollback transaction

      print '年龄不能超过15岁!'

    end

end

 

创建删除触发器

createtrigger temptrigger_delete

ontemptrigger

fordelete

as

begin

  print @@rowcount

  if @@rowcount > 1

  begin

    rollback transaction

    print '一次删除记录不能多于1条'

  end

end

自定义数据类型

       execsp_addtype ssn , 'varchar(11)' , 'NOT NULL'

       create table mytable( myidvarchar(2) primary key, myssn ssn)

特殊应用

删除重复记录

         Delete from tablename where id not in(select max(id) from tablename group by col1,col2,...)

随机数

         产生10条记录: SELECT* FROM fys ORDER BY RAND() LIMIT 0,10;

         产生随机数: SELECTFLOOR(7 + (RAND() * 6));

SQL排名

         先对该列进行排序,再通过自我链接,求出该列前有多少行

         select a1.sales, count(a2.sales) sales_remark from sales a1,salse a2 where a1.sales<=a2.sales group by a1.sales order by a1.sales desc

中位数

         将记录排序,并找出每一行的排名,找到中间排名的资源,难点是取得中间排名对应的行,可先排名,再查询

         排名=select(count(*)+1) div 2 from 表

百分比

         a1.sales/(select sum(sales) from totalsales)

每个地区人口最大国家

         select 国家 from  人口=条件(国家所在地区人口最大:  select max(population) from where 同一个地区  外表.地区=内表.地区)

         自连接  from bus b1, bus b2 where b1.num=b2.num  表示num相同的所有记录, 用于表中某一(n)列值相等情况 

分页

sql server方案1

       selecttop 10 * from t where id not in (select top 30 id from torder by id ) orde byid

sql server方案2

       selecttop 10 * from t where id in (select top 40 id from t orderby id) order by iddesc

mysql方案:

       select * from t order by idlimit 30,10

oracle方案:

       select * from (select rownum r,* from t where r<=40)wherer>30

all查询

用一条SQL语句查询出每门课都大于80分的学生姓名(一个学生多门课程)

       select name from score where name not in (select distinct name from score where fenshu<=80)  

       思路所有都大,就是有一个以上小的非

19、一个用户具有多个角色,请查询出该表中具有该用户的所有角色的其他用户。

select count(*) as num,tb.id from tb, (selectrole from tbwhere id=xxx) as t1 where tb.role = t1.role andtb.id != t1.id groupby tb.id having num = select count(role)from tb where id=xxx;

所有部门之间的比赛组合

一个叫department的表,里面只有一个字段name,一共有4条纪录,分别是a,b,c,d,对应四个球对,现在四个球对进行比赛,用一条sql语句显示所有可能的比赛组合.

select a.name,b.name from team a,team b where a.name< b.name

统计每年每月的信息

year  monthamount
1991   1     1.1
1991   2     1.2
1991   3     1.3
1991   4     1.4
1992   1     2.1
1992   2     2.2
1992   3     2.3
1992   4     2.4
查成这样一个结果
year m1  m2  m3  m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4 

提示:这个与工资条非常类似,与学生的科目成绩也很相似。

答案一、
select sales.year ,

(select t.amount fromsales t wheret.month='1' and t.year= sales.year) '1',

(select t.amount fromsales t wheret.month='1' and t.year= sales.year) '2',

(select t.amount fromsales t wheret.month='1' and t.year= sales.year) '3',

(select t.amount fromsales t wheret.month='1' and t.year= sales.year) as '4'

from sales  group by year;

显示文章标题,发帖人、最后回复时间

表:id,title,postuser,postdate,parentid

准备sql语句:

drop table if exists articles;

create table articles(id int auto_incrementprimary key,titlevarchar(50), postuser varchar(10), postdate datetime,parentidint referencesarticles(id));

insert into articles values

(null,'第一条','张三','1998-10-1012:32:32',null),

(null,'第二条','张三','1998-10-1012:34:32',null),

(null,'第一条回复1','李四','1998-10-1012:35:32',1),

(null,'第二条回复1','李四','1998-10-1012:36:32',2),

(null,'第一条回复2','王五','1998-10-1012:37:32',1),

(null,'第一条回复3','李四','1998-10-1012:38:32',1),

(null,'第二条回复2','李四','1998-10-1012:39:32',2),

(null,'第一条回复4','王五','1998-10-1012:39:40',1);

 

答案:

select a.title,a.postuser,

       (selectmax(postdate) from articles where parentid=a.id)reply

from articles a where a.parentid is null;

 发帖最多:

         selectauthorid,count(*) total from articles

group by authorid

having total=

(select max(total2) from(select count(*)total2 from articles group by authorid) as t);

 

注释:子查询可以用在选择列中,也可用于where的比较条件中,还可以用于from从句中。

删除除了id号不同,其他都相同的学生冗余信息

2.学生表如下:
id号   学号   姓名课程编号课程名称分数
1        2005001  张三 0001     数学   69
2        2005002  李四 0001     数学   89
3        2005001  张三 0001     数学   69
A: delete from tablename where id号 notin(select min(id号) from tablename group by学号,姓名,课程编号,课程名称,分数)

实验:

create table student2(id int auto_incrementprimary key,codevarchar(20),name varchar(20));

insert into student2values(null,'2005001','张三'),(null,'2005002','李四'),(null,'2005001','张三');

//如下语句,mysql报告错误,可能删除依赖后面统计语句,而删除又导致统计语句结果不一致。

delete from student2 where id not in(selectmin(id) fromstudent2 group by name);

//但是,如下语句没有问题:

select *  fromstudent2where id not in(select min(id) from student2 group by name);

//于是,我想先把分组的结果做成虚表,然后从虚表中选出结果,最后再将结果作为删除的条件数据。

delete from student2 where id not in(selectmid from (selectmin(id) mid

from student2 group by name) as t);

或者:

delete from student2 where id not in(selectmin(id) from (select* from s

tudent2) as t group by t.name);

 


你可能感兴趣的:(JOIN,sql,数据库,table,Access)