sql—在mysql中查询所有值在单个列中匹配的项

gzszwxb4  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(333)

这个问题在这里已经有答案了

在同一列上选择多个where条件(12个答案)
两年前关门了。
我试图得到一个所有项都匹配的表的结果,然后只显示它们在特定stockid中都匹配的结果。
我试着以(4,1,8)中的variantid为例,但它显示了所有结果,而不是它们都匹配4 1和8:

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

我希望它返回变量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
tnkciper

tnkciper1#

在派生表中,我们可以得到 stockId 只有
1,4,8 variantId 价值观。为了找到它,我们可以 GROUP BYstockId 并采用基于条件聚集的过滤方法 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
d8tt03nd

d8tt03nd2#

尝试以下操作:

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的其他记录。

aemubtdh

aemubtdh3#

使用 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')

相关问题