出于示例的目的,我有2个表 - 情侣表和人员表:
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
由于
答案 0 :(得分: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 :(得分: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
答案 2 :(得分: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