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.
After I get the list of Order_ID
s from the Query above I use...
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
.
Ultimately I'd like to combine these to make one query where I would just change the SalesRep_ID
A solution with proper UPDATE
syntax with JOIN
for MySql
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
Here is SQLFiddle demo
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.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.