我试图弄清楚如何在以下情况下找到所有可能的组合(使用SQL):
我想选择5个球(没有替换)如下。
如何尽可能有效地使用SQL确定所有可能的组合?
以下是我能想到的最好的,但我不想要订购(组合),我不想替换:
SELECT pick1.id, pick2.id, pick3.id, pick4.id, pick5.id, pick6.id, pick7.id, pick8.id, pick9.id
FROM bowl AS pick1, bowl AS pick2, bowl AS pick3, bowl AS pick4, bowl AS pick5, bowl AS pick6,
bowl AS pick7, bowl AS pick8, bowl AS pick9
WHERE
pick1.color = "red" AND
pick2.color = "green" AND
pick3.color = "green" AND
pick4.color = "blue" AND
pick5.color = "blue" AND
pick6.color = "blue" AND
pick7.color = "yellow" AND
pick8.color = "yellow" AND
(pick9.color = "green" OR
pick9.color = "blue" OR
pick9.color = "yellow")
答案 0 :(得分:1)
我还没有在一个实际的postgresql服务器上尝试这个,但这是一个想法。
首先,我会用整数编纂颜色:
现在,例如,我想绘制3个球:1个红色,1个绿色,1个绿色或黄色。排序后,相应的颜色代码将用作最终SQL语句的where子句中的过滤器:
[0, 1, 1]
[0, 1, 3]
然后not in (...)
基本上确保没有重复的id,并且排序的颜色数组仅限于我们在上面指定的集合。
CREATE EXTENSION intarray;
select p1.id, p2.id, p3.id
from bowl as p1
cross join bowl as p2
cross join bowl as p3
where
p2.id not in (p1.id)
and p3.id not in (p1.id, p2.id)
and sort(int[p1.color, p2.color, p3.color]) in (
int[0,1,1],
int[0,1,3]
)
intarray
功能需要sort()
扩展名。
只要您在array[]
谓词中列出所有所需的颜色组合,也可以使用不涉及intarray
和IN (..)
扩展名的变体。请参阅link。