有人可以使用工作样本/示例向我解释下面的陈述。提前谢谢。
您无法创建重复的字段,只需添加一个额外的字段“coupleId”,每个字段都有唯一的ID;每对夫妇两排(每人一人);然后用一个约束来加入表格,例如a.coupleId = b.coupleId和a.id<> b.id这样您就可以将数据压缩到给定夫妇的单个结果行中。
答案 0 :(得分:1)
根据表Person
,如下:
Person
==========
PersonID (int, autoincrement)
CoupleID (nullable int)
Name (nullable varchar(50))
插入一些行:
insert into Person (CoupleID, Name) values (1, 'John')
insert into Person (CoupleID, Name) values (1, 'Mary')
insert into Person (CoupleID, Name) values (null, 'Sue')
现在,您可以通过以下查询找到构成一对的人:
select p1.CoupleID, p1.PersonID as Person1ID, p1.Name as Person1Name, p2.PersonID as Person2ID, p2.Name as Person2Name
from Person p1
inner join Person p2 on p1.CoupleID = p2.CoupleID
where p1.PersonID <> p2.PersonID
order by p1.PersonID
输出:
PersonID CoupleID Name PersonID CoupleID Name
----------- ----------- -------------------------------------------------- ----------- ----------- --------------------------------------------------
2 1 Mary 1 1 John
1 1 John 2 1 Mary
(2 row(s) affected)