如果我连接两个表,Mysql更新查询限制不起作用

时间:2013-02-19 14:52:57

标签: mysql sql-update

在MYSQL中,如果我在连接两个表时设置更新限制,则显示

  

ERROR 1221(HY000):UPDATE和LIMIT的使用不正确

update 
       order_product_mapping as opm, 
       order_details as od, 
       product as p 
   set fullfillment='Y' 
 where 
       p.product_id=opm.product_id 
       AND od.order_id=opm.order_id 
       AND od.order_id=100 
       AND p.product_id=1 limit 1;

我的表架构是
order_details表

CREATE TABLE `order_details` (
  `order_id` int(5) NOT NULL AUTO_INCREMENT,
  `amount` int(5) DEFAULT NULL,
  `order_status` char(1) DEFAULT 'N',
  `company_order_id` int(5) DEFAULT NULL,
  PRIMARY KEY (`order_id`)
)

产品表

CREATE TABLE `product` (
  `product_id` int(5) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(50) DEFAULT NULL,
  `product_amount` int(5) DEFAULT NULL,
  `product_status` char(1) DEFAULT 'N',
  `company_product_id` int(5) DEFAULT NULL,
  PRIMARY KEY (`product_id`)
)

order_product_mapping

CREATE TABLE `order_product_mapping` (
  `product_id` int(5) DEFAULT NULL,
  `order_id` int(5) DEFAULT NULL,
  `fulfillment` char(1) DEFAULT 'N'
)

我将获得company_order_id和company_product_id作为输入,以便我进行更新查询以在order_product_mapping中更改我的履行的状态。如果在查询中添加限制则显示错误。

1 个答案:

答案 0 :(得分:2)

有关错误的解释,请参阅此帖子:https://stackoverflow.com/a/4291851/1073631

我认为我找到了解决方法/黑客攻击。加入order_product_mapping表并创建一个行号。使用行号= 1应该与LIMIT 1的工作方式相同:

UPDATE order_product_mapping opm
  JOIN (SELECT *, @rowNum:=@rowNum+1 rn FROM order_product_mapping JOIN (SELECT @rowNum:= 0) r)
    as opm2 ON opm.product_id = opm2.product_id and opm.order_id = opm2.order_id
  JOIN product p ON p.product_id=opm.product_id AND p.product_id=1
  JOIN order_details as od ON od.order_id=opm.order_id 
SET opm.fulfillment = 'Y'
where od.order_id=100 
And rn = 1;

还有一些示例小提琴:http://sqlfiddle.com/#!2/03f12/1