我在表中有一组id(列id),比如说1-10,我想结合。
我在表中有一组完全随机生成的对(列id1,id2)。
我想在单个SQL语句中找到剩余的一对夫妇。
排列非常容易,我的问题是组合而不重复。这意味着在考虑(id1,id2)==(id2,id1)或换句话说,我不知道如何找到一个不包括已更改订单的现有夫妇的集合。
有什么想法吗?
E.g。如果我有表格myids
|id|
|1 |
|2 |
|3 |
|4 |
|5 |
|6 |
|7 |
|8 |
|9 |
|10|
和表mycouples
|id1|id2|
|1 |2 |
|9 |1 |
|7 |8 |
我应该用我的陈述得到10 * 9 - 6 = 84个不同的夫妻,这是10个元素的所有可能的排列,不包括(id1 = 1,id2 = 2),(id1 = 2,id2 = 1),( ID1 = 9,ID2 = 1),(ID1 = 1,ID2 = 9),(ID1 = 7,ID2 = 8),(ID1 = 8,ID2 = 7)。
答案 0 :(得分:1)
SELECT
m1.id AS id1
, m2.id AS id2
FROM myids AS m1
JOIN myids AS m2
ON m1.id <> m2.id
WHERE NOT EXISTS
( SELECT *
FROM mycouples AS c
WHERE (c.id1, c.id2) = (m1.id, m2.id)
)
AND NOT EXISTS
( SELECT *
FROM mycouples AS c
WHERE (c.id2, c.id1) = (m1.id, m2.id)
)
答案 1 :(得分:0)
SELECT perids.* FROM (SELECT myids1.id AS id1, myids2.id AS id2
FROM (SELECT DISTINCT id FROM myids) AS myids1
INNER JOIN (SELECT DISTINCT id FROM myids) AS myids2
ON myids1.id <> myids2.id) AS perids
LEFT OUTER JOIN ((SELECT id1,id2 FROM mycouples)UNION ALL(SELECT id2,id1 FROM mycouples))
AS assoc USING (id1,id2)
WHERE assoc.id1 is NULL;
似乎可以做到这一点......(虽然^^'并不容易想到它)