gpt4 book ai didi

mysql - 选择值 x WHERE x 具有相同的未知值并且 WHERE 值 y 在数组中

转载 作者:行者123 更新时间:2023-11-29 05:30:12 24 4
gpt4 key购买 nike

我有一个存储产品组的表。

table "products_groups"

id | id_group | id_product
============================
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 1
5 | 2 | 2
6 | 3 | 2

我需要一个 SQL 查询来查找包含给定数组中所有 id_product 的 id_group。

product_ids = array(1);       // should return no results
product_ids = array(1,2); // should only return id_group 2
product_ids = array(1,2,3); // should only return id_group 1
product_ids = array(1,2,3,4); // should return no results

我四处游玩/搜索,最后停留在

SELECT p1.id_group
FROM products_groups p1, products_groups p2
WHERE p1.id <> p2.id
AND p1.id_group = p2.id_group
AND (
p1.id_product = 1
OR p1.id_product = 2
OR p1.id_product = 3
)

但它显然没有给我想要的结果。我不知道我是想得太简单了还是太复杂了。

注意:id_product 值当然会在 SQL 中动态生成。它最终将与 PHP/Codeigniter 一起使用

背景信息:每个产品都有价格,但产品可以属于具有套餐价格的产品组。这就是为什么我需要知道每个订单的产品是否在一个组中。

最佳答案

这个问题叫做Relational Division

<罢工>

<罢工>
SELECT  id_group
FROM products_groups
WHERE id_product IN (1,2)
GROUP BY id_group
HAVING COUNT(*) = 2

<罢工>

或者类似这样的东西,

SELECT  id_group
FROM products_groups
GROUP BY id_group
HAVING SUM(id_product IN (1,2)) = COUNT(*) AND
COUNT(*) = 2

关于mysql - 选择值 x WHERE x 具有相同的未知值并且 WHERE 值 y 在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15660595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com