我正在根据他们提供的产品类型将供应商记录插入到我的表中。
我正在做这样的事情;
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
RedItems (表格)
ID / Name / NumItems
1 / Smith / 23
其中NumItems是该供应商的总(红色)商品。
答案 0 :(得分:2)
我只想添加至少提供一个'Red'的供应商 项目
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
答案 1 :(得分: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
答案 2 :(得分: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