[英]Update multiple rows from results from a SELECT query to the same table
I'm trying to figure out how to combine these two queries. 我想弄清楚如何组合这两个查询。
SELECT `o`.`Order_ID`
FROM `Orders` `o`
JOIN `CustomerDetails` `cd` ON `cd`.`Customer_ID` = `o`.`Customer_ID`
WHERE `o`.`OrderPlaceServerTime` >= '2013-06-01 00:00:00'
AND `o`.`OrderPlaceServerTime` <= '2013-06-31 23:59:59'
AND `cd`.`SalesRep_ID` = 6
This gives me a list of Order_ID
s that I need to update with the SalesRep_ID = 6
from the above Query. 这给了我一个Order_ID
列表,我需要使用上面的Query中的SalesRep_ID = 6
来更新。
After I get the list of Order_ID
s from the Query above I use... 从上面的查询中获取Order_ID
列表后,我使用...
UPDATE Orders SET SalesRep_ID = '6'
WHERE (Order_ID = 541304
OR Order_ID = 541597
OR Order_ID = 542318)
Doing so updates the orders with the correct SalesRep_ID
. 这样做会使用正确的SalesRep_ID
更新订单。
Ultimately I'd like to combine these to make one query where I would just change the SalesRep_ID
最后,我想将这些组合起来进行一次查询,我只想更改SalesRep_ID
A solution with proper UPDATE
syntax with JOIN
for MySql 具有适当UPDATE
语法的解决方案,其中包含用于MySql的JOIN
UPDATE Orders o JOIN CustomerDetails d
ON d.Customer_ID = o.Customer_ID
SET o.SalesRep_ID = 6
WHERE o.OrderPlaceServerTime >= '2013-06-01 00:00:00'
AND o.OrderPlaceServerTime <= '2013-06-31 23:59:59'
AND d.SalesRep_ID = 6
You can do it in a single query by just simply combining them: 您可以通过简单地组合它们在单个查询中执行此操作:
UPDATE Orders SET SalesRep_ID = '6'
WHERE Order_ID IN (
SELECT `o`.`Order_ID`
FROM `Orders` `o`
JOIN `CustomerDetails` `cd` ON `cd`.`Customer_ID` = `o`.`Customer_ID`
WHERE `o`.`OrderPlaceServerTime` >= '2013-06-01 00:00:00'
AND `o`.`OrderPlaceServerTime` <= '2013-06-31 23:59:59'
AND `cd`.`SalesRep_ID` = 6
);
There is a little trick to this. 这有一个小技巧。 You have to fool MySQL into thinking that you are working on different tables. 你必须欺骗MySQL以为你正在研究不同的表。
UPDATE Orders SET SalesRep_ID = '6'
WHERE (Order_ID IN (SELECT order_id FROM (SELECT `o`.`Order_ID`
FROM `Orders` `o`
JOIN `CustomerDetails` `cd` ON `cd`.`Customer_ID` = `o`.`Customer_ID`
WHERE `o`.`OrderPlaceServerTime` >= '2013-06-01 00:00:00'
AND `o`.`OrderPlaceServerTime` <= '2013-06-31 23:59:59'
AND `cd`.`SalesRep_ID` = 6) AS TEMP));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.