好的,所以我有两张桌子
产品:
+------------+----------------+
| product_id | name |
+------------+----------------+
| 1 | A product here |
+------------+----------------+
| 2 | B product here |
+------------+----------------+
和卖家
+------------+----------------+------------+
| seller_id | in_stock | product_id |
+------------+----------------+------------+
| 1 | 1 | 1 |
+------------+----------------+------------+
| 2 | 0 | 1 |
+------------+----------------+------------+
| 2 | 0 | 2 |
+------------+----------------+------------+
我正在试图弄清楚如何只返回所有卖家都有in_stock = 0
的产品。
所以在这个特定的例子中,它只返回product_id为2的产品,因为product_id有一行in_stock = 1
答案 0 :(得分:1)
此产品的in_stock列的最大值必须为0:
SELECT
product_id
FROM
sellers
GROUP BY
product_id
HAVING
MAX(in_stock) = 0;
所以你通过加入获得产品信息
SELECT
*
FROM
products
INNER JOIN (
SELECT
product_id
FROM
sellers
GROUP BY
product_id
HAVING
MAX(in_stock) = 0
) t
ON
products.product_id = t.product_id;
答案 1 :(得分:0)
我会使用以下内容来说明任何卖家未出售的产品(基本上等同于没有库存),以及卖家出售但全部缺货的产品。
select product_id
from sellers
group by product_id
having max(in_stock) = 0
union all
select p.product_id
from products p
left join sellers s
on p.product_id = s.product_id
where s.product_id is null