2011-04-07 48 views
1

對於這個例子的目的,我有2個表 - 一個情侶表和個人表:是1個單查詢語句可能

Persons Table 
ID PERSON 
1 Bob 
2 Frank 
3 Sally 
4 Jane 

Couples Table 
ID HUSBAND WIFE 
1 2 3 
2 1 4 

我可以寫一個查詢語句兩個表中選擇並擁有它加入這樣一種方式,查詢結果將產生:

Couple 1 = Frank and Sally 
Couple 2 = Bob and Jane 

感謝

回答

6
SELECT Couples.ID, Husband.PERSON, Wife.PERSON 
    FROM Couples 
    INNER JOIN Persons AS Husband ON Couples.HUSBAND=Husband.ID 
    INNER JOIN Persons AS Wife ON Couples.WIFE=Wife.ID 

剛一說明,壽呃 - 這些天不是每一次婚姻都是丈夫/妻子。配偶1 &配偶2可能會更有前途。

+1

我是一個基督徒。但感謝預言。無論如何,這只是一個例子。 – 2011-04-07 15:55:44

+5

基督徒與它有什麼關係?有很多基督徒可以跟它在一起,還有很多非基督教同性戀者想結婚。 – ceejayoz 2011-04-07 16:03:01

+0

這個查詢語句像一個魅力。謝謝「ceejayoz」。 – 2011-04-07 16:14:45

2

事情是這樣的....

select m.id as husband_id, m.person as husband_name, f.id as wife_id, f.person as wife_name 
from couples c 
inner join persons m on m.id=c.husband 
inner join persons f on f.id=c.wife 
+0

這也適用。謝謝「Spudley」 – 2011-04-07 16:23:31

0
SELECT 'Couple ' + c.id + ' ' + h.person + ' and ' + w.person 
FROM Couples c 
JOIN Persons h ON h.id = c.husband 
JOIN Persons w ON w.id = c.wife