如何查询具有另一个属性更具体变化的SQL元素?
举个简单的例子: 我需要查询如何查询具有另一个属性更具体变化的SQL元素?,sql,Sql,举个简单的例子: 我需要查询Store\u IDs,它们具有Product\u ID“product1”和“product2” TableName: Storage_items +----+-------------+----------+ | ID | Product_ID | Store_ID | +----+-------------+----------+ | 1 | product1 | store1 | | 2 | product2 | store1
Store\u ID
s,它们具有Product\u ID
“product1”和“product2”
TableName:
Storage_items
+----+-------------+----------+
| ID | Product_ID | Store_ID |
+----+-------------+----------+
| 1 | product1 | store1 |
| 2 | product2 | store1 |
| 3 | product1 | store2 |
| 4 | product3 | store2 |
| 5 | product2 | store3 |
| 6 | product3 | store3 |
+----+-------------+----------+
我想,一个简单的
WHERE
语句就可以了
选择存储\u ID
从存储单元项目
其中Product_ID=“product1”
或Product_ID=“product2”
您可以使用一个简单的:
如果您想要
存储具有'product1'
和'product2'
的\u ID
以及其他产品ID
的\u ID:
SELECT Store_ID
FROM Storage_items
WHERE Product_ID IN ('product1', 'product2')
GROUP BY Store_ID
HAVING COUNT(DISTINCT Product_ID) = 2
如果您想要只包含
'product1'
和'product2'
的存储ID
s:
SELECT Store_ID
FROM Storage_items
GROUP BY Store_ID
HAVING COUNT(DISTINCT Product_ID) = 2
AND SUM(CASE WHEN Product_ID NOT IN ('product1', 'product2') THEN 1 ELSE 0 END) = 0
我需要解决这个问题的方法和条件。”IN运算符是多个OR条件的简写。“哦,对不起,我误解了,我将更新它:)不幸的是,更新后的查询仍然不起作用。WHERE中的With和in表示一条记录的属性同时具有2个值。这是不可能的:(顺便提一句,IN运算符很有帮助:)我继续搜索IN+和关键字
SELECT Store_ID
FROM Storage_items
GROUP BY Store_ID
HAVING COUNT(DISTINCT Product_ID) = 2
AND SUM(CASE WHEN Product_ID NOT IN ('product1', 'product2') THEN 1 ELSE 0 END) = 0