1. 程式人生 > >SQL語句使用總結

SQL語句使用總結

建立資料庫表,修飾關鍵字 primary key, not null, foreign key   references

create table Person(PName varchar(20),
    PAge int,
    PRemark varchar(20),
    primary key(PName));

插入資料

insert into Person(PName, PAge, PRemark) values("Jin", 18, "China")
insert into Person values("Li Chan", 23, "China")

查詢所有資料

select * from Person

更改資料

update Person set PRemark="SuperMan"
update Person set PAge=30 where PName="Jin"

刪除資料:刪除Person表的全部資料,刪除指定資料

delete from Person

delete from Person where PAge > 20 or PRemark = "Li Chan"

列表項取別名

select FNumber as Number1, FName as Name, FAge as Age from Emploee

資料彙總函式:最大值:MAX, 平均值:AVG, 求和:SUM, 最小值:MIN, 統計:COUNT(*)

select MAX(FSalary) from Employee where FAge > 25
select FDepartment, MIN(FAge) as FAgeMIN, MAX(FAge) as FAgeMAX, from Employee group by FDepartment

查詢結果升級排序或降序排序

select * from Employee order by FAge ASC

select * from Employee order by FAge DESC

select * from Employee order by FAge DESC, FSalary DESC where FAge > 23

模糊查詢,"__n_"匹配第三個字母為n的字串,字串長度為4;"T%" 匹配以"T"開頭,長度任意的字串

select * from Employee where FName like "_erry"

查詢名字不為空的所有資料

select * from Employee where FName is not null

查詢年齡不等於22歲,且工資不少於2000元的員工

select * from Employee where not(FAge=22) and not(FSalary<2000)

取出年齡是23歲,25歲,28歲的員工的資料

select FAge, FNumber, FName from Employee where FAge in(23, 25, 28)

取出年齡在23歲到27歲之間的員工資料

select * from Employee where FAge between 23 and 27

group by 子句的使用,group by 必須放到where語句之後;第二條select查詢年齡只有一個人或三個人

select FAge from Employee where FName="Huang" group by FAge

select Fage, COUNT(*) as CountOfThisAge from Employee group by FAge having COUNT(*)=1 or COUNT(*)=3

 查詢員工工資,按降序排序,取出第2到第5條資料

select * from Employee order by FSalary DESC limit 2, 5

特定查詢

select top 3 * from Employee where FNumber not in (select top 5 FNumber from Employee order by FSalary DESC) order by FSalary DESC

DISTINCT 對整個結果集進行資料復抑制

select distinct FDepartment from Employee

計算欄位可以在where 、update、delete中使用

select * from Employee where FSalary/(FAge - 21) > 1000

union all 顯示重複行

union的使用原則

  • 每個結果集必須有相同的列數
  • 每個結果集的列必須型別相同
select FNumber, FName, FAge, FDepartment from Employee
union
select FCardNumber, FName, FAge, FAddress from TemEmployee