我正在尝试获取所有项目匹配的表的结果,然后仅显示它们在特定stockid中匹配的结果。
我试图以(4,1,8)为例进行variantid,但它向我展示了所有结果,而不是它们都匹配4 1和8:
SELECT * FROM `products_bind_variant_stock_combination`
WHERE `variantId` IN (4,1,8)
我希望它能返回3个匹配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
在派生表中,我们可以获取只有1,4,8
variantId
值的所有stockId
值。为了找到这一点,我们可以在stockId
上进行GROUP BY
,并在HAVING
子句中使用基于条件聚合的过滤。
现在,我们可以使用stockId
加入主表,并获取该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 by
和 group_concat
首先查找stockid列表,然后用stockid列表过滤表。
更新,解决订购问题。
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的所有记录,其中其他带有其他变体的记录。