我正在试图弄清楚如何将这两个查询结合起来。
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
这为我提供了一个Order_ID
的列表,我需要使用上述查询中的SalesRep_ID = 6
进行更新。
从上面的查询中获取Order_ID
的列表后,我使用了...
UPDATE Orders SET SalesRep_ID = '6'
WHERE (Order_ID = 541304
OR Order_ID = 541597
OR Order_ID = 542318)
这样做会使用正确的SalesRep_ID
更新订单。
最后,我想将这些结合起来进行一次查询,我只想更改SalesRep_ID
答案 0 :(得分:5)
具有UPDATE
语法的解决方案,其中JOIN
用于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
这是 SQLFiddle 演示
答案 1 :(得分:2)
只需简单地组合它们就可以在一个查询中完成:
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
);
答案 2 :(得分:1)
这有一个小技巧。你必须欺骗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));