0

我根据他们提供的产品类型将供应商记录插入到我的表中。

我正在做这样的事情;

INSERT INTO RedItems (ID, Name, NumItems)
SELECT ID, Name, NULL
FROM supplier
WHERE status = 'Supplier'

但是,我只想添加至少提供了一件“红色”商品的供应商。

“红色”项目没有特定字段,“红色”是产品列中的一种类型。

如何以这种方式构造我的 WHERE 子句?

编辑

供应商(表)

ID    /    Name    /    Status     /     Product
1     /    Smith   /     Supplier    /    Red
2     /    Baxter   /     Supplier    /    Round

红色项目(表)

ID    /    Name    /    NumItems
1     /    Smith    /       23

其中 NumItems 是该供应商的总(红色)项目。

4

3 回答 3

2

我只想添加至少提供了一件“红色”商品的供应商

INSERT INTO RedItems (ID, Name, NumItems)
SELECT ID, Name, COUNT(Product)
FROM supplier
WHERE status = 'Supplier'
  AND Product = 'RED'
GROUP BY ID, Name
HAVING COUNT(Product) >= 1
于 2012-08-30T10:33:26.420 回答
1
INSERT INTO RedItems (ID, Name, NumItems) 
SELECT suppliers.ID, suppliers.Name, count(distinct products.id)
FROM suppliers
    inner join products on suppliers.id = products.supplierid
WHERE status = 'Supplier' and products.type='red'
group by suppliers.ID, suppliers.Name
于 2012-08-30T10:26:30.310 回答
1

如果数据在同一个表中,那么您可以执行以下操作:

INSERT INTO RedItems (ID, Name, NumItems)
SELECT ID, Name, count(product)
FROM mytable
WHERE status = 'Supplier'
  AND product = 'red'
GROUP BY ID, Name

如果没有,那么

INSERT INTO RedItems (ID, Name, NumItems)
SELECT t1.ID, t1.Name, count(p.product)
FROM mytable t1
INNER JOIN products p
   ON t1.id = p.supplierID
WHERE t1.status = 'Supplier'
   and p.product = 'red'
GROUP BY t1.ID, t1.Name
于 2012-08-30T10:26:45.910 回答