我有这个简单的SQL问题。
UPDATE parts
SET partscnt=partscnt-1
WHERE idparts = (SELECT idparts FROM ordercontent WHERE idOrder=4);
问题是子查询返回5个值,我希望对每个值进行更新。
更新: ordercontent表具有订单的ID和行idparts。如果几个相同的部分挂钩到相同的顺序,表格如下所示:
ID idparts
4 147
4 147
4 147
4 55
4 33
所以我需要为id为147的部分减少partscount三次。
如何更改此查询以实现该目标?
答案 0 :(得分:4)
尝试一下:
UPDATE parts
SET partscnt = partscnt-1
WHERE idparts IN (
SELECT idparts
FROM ordercontent
WHERE idOrder = 4
);
答案 1 :(得分:1)
查找指定订单的idparts
中每个ordercontent
的数量:
SELECT idparts,
COUNT(*) AS cnt
FROM ordercontent
WHERE idOrder = 4
GROUP BY idparts
将上述结果加入parts
并使用cnt
值更新partscnt
:
UPDATE parts p
INNER JOIN (
SELECT idparts,
COUNT(*) AS cnt
FROM ordercontent
WHERE idOrder = 4
GROUP BY idparts
) o
ON p.idparts = o.idparts
SET p.partscnt = p.partscnt - o.cnt
;
答案 2 :(得分:0)
用IN:
替换'='UPDATE parts SET partscnt = partscnt-1 WHERE idparts IN (SELECT idparts FROM ordercontent WHERE idOrder = 4);
答案 3 :(得分:0)
UPDATE parts
SET partscnt=partscnt-1
WHERE idparts IN
(SELECT idparts FROM ordercontent WHERE idOrder=4);
答案 4 :(得分:0)
UPDATE parts p1
INNER JOIN
(
SELECT *
FROM ordercontent WHERE idOrder = 4
) p2 ON p1.idparts = p2.idparts
SET p1.partscnt = p2.partscnt-1
答案 5 :(得分:-1)
将“-1”替换为“(SELECT COUNT(*)FROM ordercontent WHERE isOrder = 4)”