MySQL数据库:常见经典SQL语句
一、基礎:
1、創建數據庫:CREATE DATABASE database-name?
2、刪除數據庫:drop database dbname
3、備份sql server:
--- (1)創建備份數據的?device:
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
--- (2)開始備份
BACKUP DATABASE pubs TO testBack?
4、創建新表:
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根據已有的表創建新表:?
(1)create table tab_new like tab_old (使用舊表創建新表)
(2)create table tab_new as select col1,col2… from tab_old definition only
5、刪除數據庫表:
drop table tabname?
6、增加一個列:
Alter table tabname add column col type
注:列增加后將不能刪除。DB2中列加上后數據類型也不能改變,唯一能改變的是增加varchar類型的長度。
7、添加主鍵:?Alter table tabname add primary key(col)?
刪除主鍵:?Alter table tabname drop primary key(col)?
8、創建索引:create [unique] index idxname on tabname(col….)?
刪除索引:drop index idxname
注:索引是不可更改的,想更改必須刪除重新建。
9、創建視圖:create view viewname as select statement?
刪除視圖:drop view viewname
10、幾個簡單的基本的sql語句:
選擇:select * from table1 where?范圍
插入:insert into table1(field1,field2) values(value1,value2)
刪除:delete from table1 where?范圍
更新:update table1 set field1=value1 where?范圍
查找:select * from table1 where field1 like ’%value1%’?
11、聚合函數:(聚合函數會忽略null值)
總數:select count as totalcount 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
11、使用ANY和ALL條件:
ANY表示“任一”,ALL表示“全部”,但是ALL和ANY不能單獨使用,需要配合單行比較操作符>、>=、<、<=一起使用。
> ANY : 大于最小
< ANY:小于最大
> ALL:大于最大
< ALL:小于最小
12、使用distinct過濾重復行:SELECT DISTINCT deptno, job FROM emp;
13、使用order by排序:
SELECT <*, column [alias], …>
FROM table
[WHERE condition(s)]
[ORDER BY column [ASC | DESC]] ;
默認是ASC升序,NULL視作最大。
14、分組:Group by:
SELECT <*, column [alias], …>
FROM table [WHERE condition(s)]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column [ASC | DESC]] ;
(1)HAVING字句:
HAVING子句用來對分組后的結果進一步限制,比如按部門分組后,得到每個部門的最高薪水,可以繼續限制輸出結果。必須跟在GROUP BY后面,不能單獨存在。例如查詢每個部門的最高薪水,只有最高薪水大于4000的記錄才被輸出顯示:
SELECT deptno, MAX(sal) max_sal FROM emp
GROUP BY deptno HAVING MAX(sal) >4000;
15、如何修改數據庫的名稱:
sp_renamedb 'old_name', 'new_name'
16、?查詢語句的執行順序:
當一條查詢語句中包含所有的子句,執行順序依下列子句次序:
17、幾個高級查詢運算詞:
(1)UNION?運算符:
UNION?運算符通過組合其他兩個結果表(例如 TABLE1 和 TABLE2)并消去表中任何重復行而派生出一個結果表。當 ALL 隨 UNION一起使用時(即 UNION ALL),不消除重復行。兩種情況下,派生表的每一行不是來自 TABLE1 就是來自 TABLE2。?
(2)EXCEPT 運算符:
EXCEPT?運算符通過包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重復行而派生出一個結果表。當 ALL 隨 EXCEPT 一起使用時 (EXCEPT ALL),不消除重復行。?
(3)INTERSECT?運算符:
INTERSECT?運算符通過只包括 TABLE1 和 TABLE2 中都有的行并消除所有重復行而派生出一個結果表。當?ALL?隨 INTERSECT 一起使用時 (INTERSECT ALL),不消除重復行。?
注:使用運算詞的幾個查詢結果行必須是一致的。?
?
二、關聯查詢:
1、內連接:
內連接返回兩個關聯表中所有滿足連接條件的記錄。例如查詢員工的名字和所在部門的名字:
SELECT e.ename, d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno
或者:
SELECT e.ename, d.dname
FROM emp e JOIN dept d
ON(e.deptno = d.deptno);
2、外連接:
內連接返回兩個表中所有滿足連接條件的數據記錄,在有些情況下,需要返回那些不滿足連接條件的記錄,需要使用外連接,即不僅返回滿足連接條件的記錄,還將返回不滿足連接條件的記錄。比如把沒有職員的部門和沒有部門的職員查出來。外連接的語法如下:
SELECT table1.column, table2.column
FROM table1 [LEFT | RIGHT | FULL] JOIN table2
ON table1.column1 = table2.column2;
(1)左外連接:
(2)右外連接:
外連接查詢的例子,Emp表做驅動表:
SELECT e.ename, d.dname
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno;
Dept表做驅動表:
SELECT e.ename, d.dname
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno;
3、全連接:
全外連接是指除了返回兩個表中滿足連接條件的記錄,還會返回不滿足連接條件的所有其它行。即是左外連接和右外連接查詢結果的總和。例如:
SELECT e.ename, d.dname
FROM emp e FULL OUTER JOIN dept d
ON e.deptno = d.deptno;
4、自連接:
自連接是一種特殊的連接查詢,數據的來源是一個表,即關聯關系來自于單表中的多個列。表中的列參照同一個表中的其它列的情況稱作自參照表。
自連接是通過將表用別名虛擬成兩個表的方式實現,可以是等值或不等值連接。例如查出每個職員的經理名字,以及他們的職員編碼:
SELECT worker.empnow_empno, worker.enamew_ename, manager.empnom_empno, manager.enamem_ename
FROM emp worker join emp manager
ON worker.mgr = manager.empno;
?
三、提升:
1、復制表(只復制結構,源表名:a,新表名:b)?
法一:select * into b from a where 1<>1(僅用于SQlServer)
法二:select top 0 * into b from a
2、拷貝表(拷貝數據,源表名:a,目標表名:b)?
insert into b(a, b, c) select d,e,f from a;
3、跨數據庫之間表的拷貝(具體數據庫使用絕對路徑)?
insert into b(a, b, c) select d,e,f from b in ‘具體數據庫’ where 條件
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where..
4、子查詢(表名1:a,表名2:b)
select a,b,c from a where a IN (select d from b )?或者: select a,b,c from a where a IN (1,2,3)
5、顯示文章、提交人和最后回復時間:
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
6、between的用法,between限制查詢數據范圍時包括了邊界值,not between不包括
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between?數值1 and 數值2
7、in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)
8、兩張關聯表,刪除主表中存在,但副表中沒有的信息 :
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
9、四表聯查問題:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where?.....
10、日程安排提前五分鐘提醒 :
SQL: select * from?日程安排 where datediff('minute',f開始時間,getdate())>5
11、一條sql?語句搞定數據庫分頁:
select top 10 b.* from (select top 20?主鍵字段,排序字段?from?表名?order by?排序字段?desc) a,表名?b where b.主鍵字段?= a.主鍵字段?order by a.排序字段
12、前10條記錄:
select top 10 * form table1 where?范圍
13、選擇在每一組b值相同的數據中對應的a最大的記錄的所有信息(類似這樣的用法可以用于論壇每月排行榜,每月熱銷產品分析,按科目成績排名,等等.):
select?a,b,c?from?tablename ta?where a=(select max(a) from tablename tb where tb.b=ta.b)
14、包括所有在?TableA?中但不在?TableB和TableC?中的行并消除所有重復行而派生出一個結果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)
15、隨機取出10條數據:
select top 10 * from?tablename?order by?newid()
16、隨機選擇記錄:
select newid()
17、刪除重復記錄:
(1)delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
(2)select distinct * into temp from?tablename
delete from?tablename
insert into?tablename?select * from temp
評價: 這種操作牽連大量的數據的移動,這種做法不適合大容量但數據操作
(3)例如:在一個外部表中導入數據,由于某些原因第一次只導入了一部分,但很難判斷具體位置,這樣只有在下一次全部導入,這樣也就產生好多重復的字段,怎樣刪除重復字段:
alter table?tablename
--添加一個自增列
add?column_b?int identity(1,1)
delete from?tablename?where column_b not in(
select?max(column_b) from?tablename?group by?column1,column2,...)
alter table?tablename?drop column?column_b
18、列出數據庫里所有的表名
select name from sysobjects where type='U' // U代表用戶
19、列出表里的所有的列名
select name from syscolumns where id=object_id('TableName')
20、列示type、vender、pcs字段,以type字段排列,case可以方便地實現多重選擇,類似select 中的case。
select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type
顯示結果:
type vender pcs
電腦?A 1
電腦?A 1
光盤?B 2
光盤?A 2
手機?B 3
手機 C 3
21、初始化表table1
TRUNCATE TABLE table1
22、選擇從10到15的記錄:
select top 5 * from (select top 15 * from table order by id asc) table_別名 order by id desc
?
四、技巧:
1、1=1,1=2的使用,在SQL語句組合時用的較多:
“where 1=1”?是表示選擇全部??? “where 1=2”全部不選,
2、按姓氏筆畫排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //從少到多
3、數據庫加密:
select encrypt('原始密碼')
select pwdencrypt('原始密碼')
select pwdcompare('原始密碼','加密后密碼') = 1--相同;否則不相同 encrypt('原始密碼')
?
4、查看硬盤分區:
EXEC master..xp_fixeddrives
5、比較A,B表是否相等:
if (select checksum_agg(binary_checksum(*)) from A)
???? =
??? (select checksum_agg(binary_checksum(*)) from B)
print '相等'
else
print '不相等'
6、殺掉所有的事件探察器進程:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN('SQL profiler',N'SQL?事件探查器')
EXEC sp_msforeach_worker '?'
7、記錄搜索:
(1)開頭到N條記錄:
Select Top N * From?表
(2)N到M條記錄(要有主索引ID):
Select Top M-N * From?表?Where ID in (Select Top M ID From?表) Order by ID?? Desc
(3)N到結尾記錄:
Select Top N * From?表?Order by ID Desc
案例:
例1:一張表有一萬多條記錄,表的第一個字段 RecID 是自增長字段, 寫一個SQL語句, 找出表的第31到第40個記錄。
select top 10 recid from A where recid not in(select top 30 recid from A)
分析:如果這樣寫會產生某些問題,如果recid在表中存在邏輯索引。
select top 10 recid from A where……是從索引中查找,而后面的select top 30 recid from A則在數據表中查找,這樣由于索引中的順序有可能和數據表中的不一致,這樣就導致查詢到的不是本來的欲得到的數據。
解決方案:
(1)用order by?select top 30 recid from A order by ricid?如果該字段不是自增長,就會出現問題
(2)?在那個子查詢中也加條件:select top 30 recid from A where recid>-1
8、獲取當前數據庫中的所有用戶表:
select Name from sysobjects where xtype='u' and status>=0
9、獲取某一個表的所有字段:
select name from?syscolumns?where id=object_id('表名')
select name from?syscolumns?where id in (select id from?sysobjects?where type = 'u' and name = '表名')
兩種方式的效果相同。
10、查看與某一個表相關的視圖、存儲過程、函數:
select a.* from?sysobjects?a,?syscomments?b where a.id = b.id and b.text like '%表名%'
11、查看當前數據庫中所有存儲過程:
select name as?存儲過程名稱 from?sysobjects?where xtype='P'
12、查詢用戶創建的所有數據庫:
select * from master..sysdatabases?D where sid not in(select sid from master..syslogins?where name='sa')
或者
select dbid, name AS DB_NAME from master..sysdatabases?where sid <> 0x01
13、查詢某一個表的字段和數據類型:
select column_name,data_type from information_schema.columns
where table_name = '表名'
?
?
文章轉自:
https://www.cnblogs.com/1234abcd/p/5530314.html
http://pdf7.tarena.com.cn/tts8_source/ttsPage/JAVA/JSD_N_V06/ORACLE/DAY03/SUPERDOC/01/index.html#page_top_superdoc
總結
以上是生活随笔為你收集整理的MySQL数据库:常见经典SQL语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java集合篇:HashMap原理详解(
- 下一篇: MySQL数据库:drop、trunca