3

我试图弄清楚如何组合这两个查询。

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上述查询更新的 s 列表。

从上面的查询中获得 s 列表后Order_ID,我使用...

UPDATE Orders SET SalesRep_ID =  '6'
WHERE  (Order_ID = 541304
OR  Order_ID = 541597
OR  Order_ID = 542318)

这样做会使用正确的SalesRep_ID.

最终,我想将这些结合起来进行一个查询,我将在其中更改SalesRep_ID

4

3 回答 3

6

具有正确UPDATE语法的解决方案JOINfor 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演示

于 2013-08-07T15:30:04.050 回答
3

您可以通过简单地组合它们在单个查询中完成:

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
);
于 2013-08-07T15:19:29.550 回答
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));

链接到 SQLFiddle

于 2013-08-07T15:19:27.673 回答