2011-04-07 45 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