常用sql語句總結

1.創建一張與已經存在表的結構以及數據一樣的表:

   create table test1 as select * from student;

2.創建一張與已經存在表的結構一樣的空表:

   create table test1 as select * from student where 1=2;

3.倆張表的結構一樣將其中一張表的數據導入另一張表:

   insert into test2 select * from test1;

4.將另一張表的某幾列數據導入到另一張表中對應的列:

   insert into test3(sid,sname) select sid,sname from test2;

5.插入數據:

   insert into student(sid,sname,sage) values('1','小李',27);

6.修改數據:

   update student set name='小王' ,sage='28' where  sid='1';

7.刪除數據:

   delete from student where sid='1';

8.刪除表中所有的數據並且釋放空間,表的索引將重新設置成初始大小:

   truncate table student;

9.刪除表結構和數據:

   drop table student;

10.表中添加列並添加註釋:

   alter table student add address varchar(100) comment '地址';

11.修改列的名字,並添加列註釋:

   alter table tb_vehicle_model change column  tb_vehicle_brand_id  vehicle_brand  varchar(32);
   alter table tb_vehicle_model modify column vehicle_brand varchar(32) comment '車品牌'; 

12.修改列的數據類型:

   alter table tb_maintence_station  MODIFY column  id varchar(32);

13.刪除列:

   alter table th_push_message drop is_read;

14.根據子查詢更新:

   update tb_vehicle SET status = '1' where id in(select a.id from(select id from tb_vehicle where status = '0') a);

15.主表中存在但從表中不存在數據,但是要查詢出具體哪個主表的數據不在從表中:

   select * from student a left join student_cource b on a.sid=b.sid where b.cid is null;

16.獲取多少條到多少條數據(mysql寫法,第一個參數爲起始位置,第二個參數爲獲取的條數):

   select * from student_cource limit 0,5;

17.獲取多少條到多少條數據(oracle寫法):

   select * from (select rownum rn,cn.* from student cn) where rn BETWEEN 10 and 20;

18.彙總語句:

    select
       a.sname,
       sum(case when b.courcename='語文' then c.score else null end) 語文
       sum(case when b.courcename='數學' then c.score else null end) 數學,
       sum(case when b.courcename='英語' then c.score else null end) 英語,
       sum(case when b.courcename='物理' then c.score else null end) 物理,
       sum(case when b.courcename='化學' then c.score else null end) 化學,
       sum(c.score) total,
       round(avg(c.score),2) avg
   from student a,cource b,student_cource c where a.sid=c.sid and b.cid=c.cid group by a.sname;

19.刪除表中姓名重複的記錄(單個字段),並且保留ID最小的記錄( mysql寫法):

delete from  test1 where 

sname in ( select  b.sname from  (select sname from test1 group by sname having count(sname)>1) b)

and 

sid not in(select  a.sid from  (select min(sid) sid from test1 group by sname having count(sname)>1) a );

20.刪除表中姓名重複的記錄(單個字段),並且保留ID最小的記錄 (oracle寫法):

delete from test1 where 

sname in (select t.sname from test1 t group by  t.sname having count(t.sname)>1 )

and

 sid not in  (select min(b.sid) from test1  b group by b.sname having count(b.sname)>1 );

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章