[英]Sql Query to get an item that contains multiple ids from another table
I have three tables.我有三张桌子。 Container, Inventory and SKU
容器、库存和 SKU
Container table集装箱桌
ContainerId![]() |
---|
C1 ![]() |
C2 ![]() |
C3 ![]() |
Inventory Table库存表
InventoryId![]() |
Sku![]() |
Container![]() |
---|---|---|
I1 ![]() |
S1 ![]() |
C1 ![]() |
I2 ![]() |
S1 ![]() |
C2 ![]() |
I3 ![]() |
S2 ![]() |
C1 ![]() |
SKU Table SKU表
SkuId ![]() |
---|
S1 ![]() |
S2 ![]() |
S3 ![]() |
I need to create a sql query that will return the container(s) that contains all of the given SKU ids.我需要创建一个 sql 查询,该查询将返回包含所有给定 SKU id 的容器。 So if I want the containers that have SKU S1, my results should be C1 and C2 but if I want to get the containers that have SKU ids S1 and S2 my only result should be C1.
因此,如果我想要具有 SKU S1 的容器,我的结果应该是 C1 和 C2,但是如果我想要获得具有 SKU id S1 和 S2 的容器,我唯一的结果应该是 C1。 C2 should not be a result because it does not have S2.
C2 不应该是结果,因为它没有 S2。
So far the query I have tried is到目前为止,我尝试过的查询是
SELECT distinct containerId FROM Container c
JOIN Inventory i ON i.Container = c.ContainerId
JOIN SKU s ON s.SkuId = i.Sku
WHERE s.SkuId IN (S1, S2)
But the WHERE IN statement is a shorthanded OR so it will return C2 as a result too because it contains S1.但是 WHERE IN 语句是一个简写的 OR,因此它也会返回 C2 作为结果,因为它包含 S1。
I know there is no way to shorthand an AND condition but is there a similar way or a possible way to do this?我知道没有办法简写 AND 条件,但是有没有类似的方法或可能的方法来做到这一点?
Instead of distinct, you use group by and use count to verify that all required skus were present:您使用 group by 和 count 来验证所有必需的 skus 是否存在,而不是 distinct :
SELECT c.ContainerId
FROM Container c
JOIN Inventory i ON i.Container = c.ContainerId
JOIN SKU s ON s.SkuId = i.Sku AND s.SkuId in (S1, S2)
GROUP BY c.ContainerId
HAVING COUNT(DISTINCT s.SkuId)=2
But, as commented by others, there's no need to use any table but Inventory:但是,正如其他人评论的那样,除了 Inventory 之外,不需要使用任何表:
SELECT i.Container
FROM Inventory i
WHERE i.Sku in (S1, S2)
GROUP BY i.Container
HAVING COUNT(DISTINCT i.Sku)=2
You don't actually need any joins for this query, for the results you specify in the question:对于您在问题中指定的结果,您实际上不需要此查询的任何连接:
SELECT i.Container
FROM Inventory i
WHERE i.Sku in (S1, S2)
GROUP BY i.Container
HAVING COUNT(i.Sku) = 2;
You only need COUNT(DISTINCT)
if a container could have multiple rows for the same SkuId
.如果容器可以有多个行用于同一个
SkuId
则您只需要COUNT(DISTINCT)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.