我有一张Products
桌子
有ProductId
和StatusId
列
如何选择具有StatusId
1 和 2(两行)的所有产品?
要选择具有两种状态 (1,2) 的产品:
SELECT ProductId
FROM products
WHERE status IN (1, 2)
GROUP BY ProductId
HAVING COUNT(distinct status) = 2
尝试此查询以获取同时具有状态 1 和 2 的产品的记录
SELECT DISTINCT a.ProductId
FROM Products a, Products b
WHERE a.ProductId = b.ProductId
AND a.StatusId = 1
AND b.StatusId = 2;
使用 ANSI 连接
SELECT DISTINCT a.ProductId
FROM Products a INNER JOIN Products b
ON a.ProductId = b.ProductId
WHERE a.StatusId = 1
AND b.StatusId = 2;
SELECT DISTINCT a.ProductId
FROM Products a
INNER JOIN Products b ON a.ProductId = b.ProductId
WHERE a.StatusId IN (1, 2)