查询 MYSQL 中单个列中所有值都匹配的项目

Querying items where ALL values match in a single column in MYSQL

我正在尝试获取 table 的结果,其中所有项目都匹配,然后仅显示它们在特定 stockId 中全部匹配的结果。

我尝试以 variantId IN (4,1,8) 为例,但它向我显示了所有结果,而不是它们全部匹配 4 1 AND 8:

SELECT * FROM `products_bind_variant_stock_combination` 
WHERE `variantId` IN (4,1,8) 

我希望它 return 变体 ID 匹配 4、1 和 8 的 3 个结果。或者我只想显示 ID 匹配所有这些的股票 ID。

我的结构在

products_bind_variant_stock_combination


|subId        |int(10)|No |
|productsId   |int(10)|Yes|NULL
|stockId      |int(10)|Yes|NULL
|variantId    |int(10)|No |

小样本是:

|1|69|1|4
|2|69|1|1
|3|69|1|8
|4|69|2|5
|5|69|2|1
|6|69|2|8
|7|69|3|6
|8|69|3|1
|9|69|3|8

搜索variantId匹配4,1,8我想要的结果是:

|1|69|1|4
|2|69|1|1
|3|69|1|8

Derived Table中,我们可以得到所有只有1,4,8 variantId值的stockId值。为了找到它,我们可以在 stockIdGROUP BY 并在 HAVING 子句中使用基于条件聚合的过滤。

现在,我们可以使用 stockId 连接回主 table 并获取该 stockId 值的所有行。

SELECT
  t1.*
FROM products_bind_variant_stock_combination AS t1
JOIN (SELECT stockID
      FROM products_bind_variant_stock_combination
      GROUP BY stockID 
      HAVING SUM(variantId = 1) AND /* has variantId = 1 */
             SUM(variantId = 4) AND /* has variantId = 4 */
             SUM(variantId = 8) AND /* has variantId = 8 */
             NOT SUM(variantId NOT IN (1,4,8)) /* no other variantId exists */
     ) AS t2 ON t2.stockId = t1.stockID 

首先使用group bygroup_concat找出stockId列表,然后用stockId列表过滤table。

已更新,解决排序问题。

select * from `products_bind_variant_stock_combination`
where stockId in (select stockId 
                    from `products_bind_variant_stock_combination` 
                    group by stockId 
                    having group_concat(variantId order by stockId) = '1,4,8')

尝试这样的事情:

select * from products_bind_variant_stock_combination p
where 
  exists (select 1 from products_bind_variant_stock_combination p2 where p2.stockId = p.stockId and  variantId=1)
  and exists (select 1 from products_bind_variant_stock_combination  p2 where p2.stockId = p.stockId and variantId=4)
  and exists (select 1 from products_bind_variant_stock_combination  p2 where p2.stockId = p.stockId  and variantId=8);

它为您提供具有相同 stockId 的所有记录,其中存在具有其他 variantId 的其他记录。