2013-10-17 43 views
3

我有以下兩個表:返回一個表中的所有行,並與另一個表中的行的子集匹配?

rsrpID rsrpName 
1  Library Catalog 
2  Interlibrary Loan 
3  Academic Search Complete 
4  JSTOR 
5  Project Muse 
6  LibGuides 
7  Web Resource 
8  Other (please add to Notes) 
9  Credo Reference 

rsriID rsrirsrpID rsrisesdID 
603  6   243 
604  1   243 
605  7   243 
606  8   244 
607  6   245 
608  8   245 

我試圖做的是恢復整個第一表,並在第二個表中的第一個表匹配rsrpID那些行,返回這些對相關行旁邊的第一個表,例如:

rsrpID rsrpName     rsrisesdID 
1  Library Catalog    243 
2  Interlibrary Loan   
3  Academic Search Complete  
4  JSTOR      
5  Project Muse     
6  LibGuides     243 
7  Web Resource    243 
8  Other (please add to Notes) 
9  Credo Reference    

...但我不能爲我的生活弄清楚,會返回此連接語句。目前我得到的查詢是

select rp.rsrpID as ID, rp.rsrpName as Name, 
    (select if((count(rsrisesdID) > 0), 'checked', '') 
     from resourcesintroduced ri 
     where (ri.rsrirsrpID = rp.rsrpID) 
      and (rsrisesdID = 243)) as 'checked' 
    from resourcesintroduced ri, 
    resourcepool rp 
where rsrisesdID = 243 
group by ID 
order by Name asc; 

正如你可以看到,查詢是笨重,如果一個特定的rsrisesdID沒有出現的話,那麼查詢都沒有返回行。

+0

LEFT OUTER JOIN:這將有助於(http://www.codinghorror.com/blog/2007/10/a-visual-explanation- of-sql-joins.html)對你很好的描述。 – Ben

回答

6

你正在尋找一個外部聯接:

select rp.rsrpID as ID, rp.rsrpName as Name, ri.rsrisesdID 
    from resourcepool rp 
    left outer join resourcesintroduced ri on (ri.rsrirsrpID = rp.rsrpID and ri.rsrisesdID = 243) 
+1

就是這樣。我想我對SQL甚至沒有足夠的瞭解,甚至想過在那裏做一個這樣的測試。可能是這個項目的這個部分超過了我的頭...... – wmassingham

1

您使用LEFT JOIN

SELECT 
    rsrpID, 
    rsrpName, 
    vrsrisesdID 
FROM 
    rp LEFT JOIN 
    ri ON rp.rsrpID = ri.rsrirsrpID 

將返回:

1 Library Catalog     243 
2 Interlibrary Loan    NULL 
3 Academic Search Complete  NULL 
4 JSTOR       NULL 
5 Project Muse     NULL 
6 LibGuides      245 
6 LibGuides      245 
7 Web Resource     243 
8 Other (please add to Notes)  244 
8 Other (please add to Notes)  245 
9 Credo Reference     NULL 

根據DBMS的味道,你可能必須使用LEFT OUTER JOIN

希望這會有所幫助!

+0

事實上,在'resourcesintroduced'中返回_all_行,並加入'resourcepool'。我仍然可以通過'rsrisesdID'進行過濾以獲得我需要的行,但是我沒有在任何地方獲得我需要的空值。 – wmassingham

相關問題