文章目錄
開始之前需要導入一些表,下載地址:https://yuyunyaohui.lanzous.com/ivPKcdnlecd
導入方法:https://blog.csdn.net/hyh17808770899/article/details/106744978
1、基本查詢語句
SELECT [DISTINCT] column_name1,…|*
FROM table_name
[WHERE conditions]
2、在SQL PLUS中設置格式
COLUMN column_name HEADING new_name
//注:COLUMN 可以簡寫成 COL
col username heading 用戶名;
select * from sys_user;
COLUMN column_name FORMATE dataformat
注:字符類型只能設置顯示的長度
col username format a10;
select * from sys_user;
col salary format 9999.9;
select * from sys_user;
col salary format $9999.9;
select * from sys_user;
COLUMN column_name CLEAR
col username clear;
col salary clear;
select * from sys_user;
3、查詢表中的所有字段及指定字段
col userid heading 用戶編號;
col username heading 用戶名;
col salary heading 工資;
select * from sys_user;
select username,salary from sys_user;
4、給字段設置別名(針對查詢結果進行的,並不更改字段的名字)
SELECT column_name AS new_name,…
FROM table_name
注意:AS可以省略,用空格隔開原來的字段名和新字段名即可
select userid as 編號, username as 用戶名,salary 工資
from sys_user;
select distinct username as 用戶
from sys_user;
5、運算符和表達式
Oracle中的操作數可以有變量、常量和字段
算術運算符(+, -, *, /)
比較運算符(>, >=, <, <=, =, <> )
邏輯運算符( not, and, or )
6、在SELECT語句中使用運算符
(1)使用算術運算符
select userid, username,salary+200
from sys_user;
(2)使用比較運算符
select username from sys_user where salary < 900;
(3)使用邏輯運算符
select username
from sys_user
where salary > 800 and salary <> 990.8;
比較運算符的優先級高於邏輯運算符
7、帶條件的查詢
(1)單一條件查詢
select salary
from sys_user
where username='李四';
select username,salary
from sys_user
where userid = 2;
(2)多條件查詢
select * from sys_user
where username ='李四'
or salary > 1000;
8、模糊查詢
LIKE
通配符的使用(_, %)
一個_只能代表一個字符
%可以代表0到多個字符
使用LIKE查詢
查詢用戶名以“李”開頭的用戶信息
select * from sys_user where username like '李%';
查詢用戶名的第二個字符是“四”的用戶信息
select * from sys_user where username like '_四%';
查詢用戶名中含有“小”的用戶信息
select * from sys_user where username like '%小%';
9、範圍查詢
例:查詢800到1000之間的員工工資
BETWEEN…AND
select * from sys_user where salary between 800 and 1000;
select * from sys_user where salary not between 800 and 1000;
IN/NOT IN
例:查詢用戶名是“張三”或者“李四”的用戶信息
select * from sys_user where username in('張三','李四');
select * from sys_user where username not in('張三','李四');
10、對查詢的結果排序
SELECT….FROM.…[WHERE…]
ORDER BY column1 DESC/ASC, …
select * from sys_user order by userid desc;
select * from sys_user order by username desc,salary asc;
11、case…when 語句的使用
CASE column_name
WHEN value1 THEN result1,…
[ELSE result] END
select username,case username when '張三' then 'sss部門'
when '李四' then 'xxx部門' else 'other部門' end as 部門
from sys_user;
CASE
WHEN column = value1
THEN result1,… [ELSE result] END
select username,case when username = '張三' then 'sss部門'
when username = '李四' then 'xxx部門' else 'other部門' end as 部門
from sys_user;
select username,case when salary < 900 then '工資低'
when salary > 1000 then '工資高' end as 工資水平
from sys_user;
12、decode函數的使用
decode(column_name, value1, result1,
…, defaultvalue)
select username, decode(username, '張三', 'sss部門', '李四', 'yyy部門', '其他')as 部門
from sys_user;