[英]Grabbing data from ORACLE DB
我有一個數據庫,其中包含Author(id,name),AuthorPublication(aid,pid),Publication(id,title)
Author.id鏈接到AuthorPublication.aid,AuthorPublication.pid鏈接到Publication.od。
我正在嘗試編寫一個查詢,該查詢返回與“ amol”或“ samuel”共同創作的作者的名字,但兩者都不是。
到目前為止,我有
Select name
From Author, AuthorPublication, Publication
Where Publication.id = PID AND aid = Author.id
在上面的代碼中,我需要將PID過濾為pid與作者“ samuel”或“ amol”匹配的作者。 但不是兩者
作為oracle db的新手,我不太確定如何實現此功能,有什么幫助嗎?
提前致謝!
在您的where子句中嘗試: and (author.name = 'samuel' and author.name != 'amol') OR (author.name != 'samuel' and author.name = 'amol')
(根據https:/ /community.oracle.com/thread/2342467?tstart=0 )。
邏輯? 基本上,獲取兩個作者的ID,獲取其出版物的任何pid,這些pid不能相同....然后使用生成的出版物ID。 1個查詢中有幾種方法可以執行此操作,這是一種使用表別名在一個查詢中多次使用表的方法:
select auth_sam.name as sams_name
,auth_amol.name as amols_name
,nvl(auth_sam.name, auth_amol.name) as single_author_name
,s_pubinfo.title as sam_publication_titles
,a_pubinfo.title as amol_publication_titles
,nvl(s_pubinfo.title, a_pubinfo.title) as single_pub_name
from author auth_sam
,authorPublication sam_pubs
,publication s_pubinfo -- 3 aliases for samuel data
,author auth_amol
,authorPublication amol_pubs
,publication a_pubinfo -- 3 aliases for amol data
where auth_sam.name = 'samuel'
and auth_sam.id = sam_pubs.aid -- pubs by samuel
and sam_pubs.pid = s_pubinfo.id -- samuel titles
and auth_amol.name = 'amol'
and auth_amol.id = amol_pubs.aid -- pubs by amol
and amol_pubs.pid = a_pubinfo.id -- amol titles
and sam_pubs.pid != amol_pubs.pid -- not the same publication
由於!=
,該查詢有效地返回2組結果。 “ samuel”的記錄將填充“ sams_name”列,而“ amols_name”列將為空。 “ amol”的記錄將填充其“名稱”列,而“塞繆爾名稱”列的值將為null。 由於這些空值,我使用NVL()
包括了兩列,以演示選擇要顯示哪個作者字段值和標題字段值的方法。 (這不是一個非常“干凈”的解決方案,但我認為它展示了有關關系邏輯和SQL功能的一些見解。)
順便說一句-在這個例子中,我真的認為SQL使用Oracle SQL語法更具可讀性。 帶有所有JOIN
和ON
關鍵字的ANSI SQL版本對我來說更難理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.