sql最常用命令陳述句總結
我們以student表為例:
基本查詢

- 表全部資訊:
select * from 表名稱; //*可以理解代表全部
eg:
我們查詢整個student表:
select * from student;
結果如下:

- 檢索查詢
SELECT 列名稱 FROM 表名稱
eg:
我們檢索全體學生的學號、姓名:
Select Sno,Sname from student;
結果如下:

查詢時改變列標題的顯示(取別名)
Select column1 as column1`,column2 as column2` from student;
eg:
我們檢索全體學生的學號、姓名、性別資訊,并分別加上“學號”、“姓名”、“性別”的別名資訊:
Select Sno as 學號,Sname as 姓名,Ssex as 性別 from student;
結果如下:

條件查詢
SELECT 列名稱 FROM 表名稱 WHERE 列 運算子 值;
eg1:
我們查詢成績大于90分的學生的學號及課程號、成績:
Select * from Student where Grade>90;
結果如下:

運算運算子:

eg2:
我們查詢成績介于85~90分的學生的學號及課程號、成績:
Select * from Student where Grade between 85 and 90;

我們查詢成績不介于90~95分的學生的學號及課程號、成績:
Select * from Student where Grade not between 90 and 95;
結果如下:

eg3:
我們查詢選修了課程號為“2”,且成績大于88的學生的學號:
Select * from Student where Cno = '2' and Grade > 88;
結果如下:

Select * from Student where Cno = '2' or Cno = '3';
結果如下:

基于IN子句的資料查詢
SELECT 列名
FROM 表名
WHERE 列名 IN (value1,value2,...)
eg:
我們從student表中查詢出劉晨,李勇的所有資訊:
Select * from Student where Sname in ('李勇','劉晨');
結果如下:

基于Like子句的查詢

- 使用%通配符
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
eg:
我們從學生表中分別檢索出姓張的所有同學的資料:
Select * from Student where Sname like '劉%'; //%代表缺少的東西,可定義通配符
結果如下:

- 使用 _ 通配符
我們檢索名字的第二個字是“勇”的所有同學的資料:
Select * from Student where Sname like '_勇%';
結果如下:

eg:
我們檢索名字的包含字是“勇”的所有同學的資料:
Select * from Student where Sname like '%勇%';
結果如下:

特殊情況
eg:
如果用戶查詢的匹配字串本身就含有%或_,比如亂寫名字的,像:謝 _穎,李%峰,我們要通過姓名查詢上面同學的學號:
用 escape
Select Sno from Student where Sname like '謝/_穎' escape'/';
Select Sno from Student where Sname like '李/%峰' escape'/';
- 使用 [charlist] 通配符
eg:
我們希望選出名字以“A",“L”開頭的外國人人的所以資料:
Select * from Student where Sname like '[AL]%';
我們不希望選出名字以“A",“L”開頭的外國人人的所以資料:
Select * from Student where Sname like '[!AL]%';
使用top關鍵字查詢
SELECT TOP number|percent column_name(s)
FROM table_name;
eg:
我們從Student表中檢索出前3個學生資訊:
Select top 3 * from Student;
我們從Student表中檢索出前50%學生資訊:
Select top 50 percent * from Student;
消除重復行
用 distinct
eg:
Select distinct Sno from Student;
結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/200802.html
標籤:其他
