長期收集遇到的ORACLE 語句問題


1、在表中檢索出來的數據前後添加字符

eg:

<pre class="sql" name="code">table

id           name             ps

1            demo         123456

2            lions         123456

要檢索出"土豪的demo","lions是窮逼"

select  '土豪的'||t.name from table t;

select t.name||'是窮逼' from table t;

裸照用遇到這個問題是在表的遷移時,需要在所有的屬性前加上前綴,此方法還是很有效的

在sql中用的是

select concat('土豪的',t.name) from table t

select concat(t.name,'是窮逼',) from table t

2、字符的截取

eg:

id           name             ps

1            土豪的demo         123456

2            lions是傻逼         123456
只要檢索出demo和lions
select substr(t.name,4) from table t

select substr(t.name,0,5) from table t


3、集合

eg:

table1

id           name             ps

1            demo         123456

2            lions         123456

table2

id           name            ps

1             demo         123456

2            zebra         123456

只要檢索出zebra和lions

<span style="color: #000000;">常用並集union、union all,但是被問到差集怎麼查詢,第一反應是</span>

select name from table1 where name not in(select name from table2)

union

select name from table2 where name not in(select name from table1)

但是,想想這樣子的效率好像有點問題啊多個select還要where  not in,效率肯定是有點問題的

然後就查詢了一下,發現了居然還有<strong><span style="color: #ff0000;">minus</span></strong>這個關鍵字。如下:

select name from table1 minus select name from table2

union

select name from table2 minus select name from table1

額,我想爲什麼沒有直接一個關鍵字就可以解決差集的問題呢

4、更新還是插入:

數據name=demo,在數據庫層次判斷是要插入還是更新,當數據庫已經存在name=demo時,則爲修改,否則爲插入

table

id           name         ps

1            demo         123456

2            lions         123456

merge into table d

using (select name from table where name='demo')s

on(d.name=s.name)

when matched then

update set d.ps='123'

when not matched then

insert(d.name,d.ps)values('demo','123');

5、深度查詢:
     在一張表內存在id 和parented,根據id找到所有的子孫節點,這是一個深度迭代
WITH tab AS (
	SELECT
		DepartmentId,
		ParentId
	FROM
		Base_Department
	WHERE
		DepartmentId = '' --父節點
	UNION ALL
		SELECT
			b.DepartmentId,
			b.ParentId
		FROM
			tab a,--父節點數據集
			Base_Department b --子節點數據集
		WHERE
			b.ParentId = a.DepartmentId --子節點數據集.ID=父節點數據集.parendID
)select * from OA_EmpLeave where DepartmentId in( SELECT
	tab.DepartmentId
FROM
	tab);

6、廣度迭代和深度迭代:


深度查詢:select * from table start with pid = 0 connect by prior id = pid;
廣度遍歷:select * from table start with pid = 0 connect by prior id = pid order by level;
 

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