简体   繁体   中英

Grabbing data from ORACLE DB

I have a database which has Author(id, name), AuthorPublication(aid, pid), Publication(id, title)

Author.id links to AuthorPublication.aid, AuthorPublication.pid links to Publication.od.

I am trying to write a query that returns the name of authors who has co-authored with "amol" or "samuel" BUT NOT BOTH.

So far I have

Select name 
From Author, AuthorPublication, Publication
Where Publication.id = PID AND aid = Author.id 

In the above code I need to filter the PID to be authors whose pid matches author "samuel" or "amol". But not both

Being new to oracle db, Im not so sure how to implement this, any help?

Thanks in advance!

在您的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 )。

Logic? Basically, get the id of the two authors, get any pid of their publications, those pids can't be the same....then use the resulting publication ids. There are several ways to do this in 1 query, here's one way using table aliases to use tables more than once in one query:

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

Because of the != , the query effectively returns 2 sets of results. Records for 'samuel' will have the 'sams_name' column populated and the 'amols_name' column will be null. Records for 'amol' will have his name column populated and the samuel name column value will be null. Because of these nulls, I included two columns using NVL() to demonstrate a method to choose which author field value and title field value to display. (Not a very "clean" solution, but I think it demonstrates several insights in the power of relational logic and SQL.)

btw - in this example, I really think the SQL is more readable with the Oracle SQL syntax. The ANSI SQL version, with all the JOIN and ON keywords, feels more difficult to read to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM