我有一张产品表和另一张这些产品的具体 list .

CREATE TABLE products (id INT AUTOINCREMENT);
CREATE TABLE listings (
  id INT AUTOINCREMENT,
  product INT REFERENCES products(id),
  vendor INT
)

我想 Select 一组产品的上市,这样他们是由不同的供应商的最小计数出售.例如:

id 产品 供应商
1 1 1
2 1 2
3 2 3
4 2 1
5 3 4

对于产品(1,2,3),我希望获得ID (1,4,5).有没有一种只使用SQL就能实现这一点的方法?或者,我应该简单地使用多个查询并在其他地方组合结果吗?

推荐答案

不幸的是,正如我在 comments 中解释的那样,您试图解决的问题看起来像是一个NP完全问题,您已经正确地将其标识为set-cover problem.

这意味着您不能在多项式时间内解决一般情况.

Conclusion:
Let alone maintainabilty of complex SQL queries, you probably do not want to run anything with exponantial complexity on a database; I recommend you compute the solution elsewhere, using a language and an algorithm more suitable for the task than SQL can do.
Finding an approximation of the solution can be done in polynomial time (explained in the link above). That could theoretically be done using not-too-complex SQL queries (possibly using one of the queries posted as answers, I have not checked) but even then, I would not recommend that path; better doing it outside of the database.

Sql相关问答推荐

用相同值更新行

连接三个表的正确方式是什么?在这三个表中,可以显示在一个表上的行将在其他表中显示结果

不同表达方式时的大小写

SQL:如何将相应位置的两个数组中的元素组合在一起

每年独特口味的冰淇淋数量

使用多个嵌套数组查询JSON数据

如何根据行状态设置正确的标志

Netezza SQL:判断两个表是否相同

使用多个数据库调用重载 CQRS 模式

SQL 根据前一天的最大值计算每天的值数

SQL Server - 复杂场景 - 比较状态并填充值到后续行

SQL 将 Varchar 转换为日期

基于字符串的SQL查询

使用ALTER TABLE无法删除列

如何在插入时将字符串'03-January-2023'转换为日期时间

Clob 问题 - 将 clob 列拆分为多行

使用 GROUP BY 时如何创建其他组?

在 MySql 数据库中的两个日期之间搜索

有条件求和

REGEXP 用于字符串格式化以对用空格分隔的字符和数字进行分组