MySQL UPDATE与唯一键冲突

时间:2010-12-15 19:05:11

标签: mysql insert-update

表格如下:

CREATE TABLE `ToursCartsItems` (
  `Id` int(10) unsigned NOT NULL auto_increment,
  `UserId` char(40) default NULL,
  `TourId` int(10) unsigned NOT NULL,
  `CreatedAt` int(10) unsigned default NULL,
  PRIMARY KEY  (`Id`),
  UNIQUE KEY `UniqueUserProduct` (`UserId`,`TourId`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED

// simple sample data
INSERT INTO
    ToursCartsItems (UserId, TourId)
VALUES
    ("old", 1), ("old", 2), ("new", 1), ("new", 3);

因此,一个用户可以拥有多个游览(更别提哪些游览了)。 UserId字段是char,而不是int,因为用户可能没有登录,在这种情况下会使用会话ID。

当用户登录时,其UserID会发生变化。所以简单的更新将是

UPDATE ToursCartsItems SET UserId="new" WHERE UserId="old"
-- In reality, the new UserId would be an integer, but never mind that.

但这可能会提供重复的输入密钥。如果旧用户和新用户都有相同的游览,我们应该在更新前删除一个。

所以我试过

UPDATE ToursCartsItems
    SET UserId="in"
    WHERE UserId="out"
    AND (TourId NOT IN (SELECT TourId FROM ToursCartsItems WHERE UserId="in")
);
DELETE FROM ToursCartsItems WHERE UserId="old";

TRUNCATE ToursCartsItems;
INSERT INTO ToursCartsItems (UserId, TourId) VALUES ("old", 1), ("old", 2), ("new", 1), ("new", 3);
DELETE FROM ToursCartsItems WHERE UserId="old" AND TourId IN (SELECT TourId FROM ToursCartsItems WHERE UserId="new");
UPDATE ToursCartsItems SET UserId="new" WHERE UserId="old";

两者都给我错误。有没有办法在SQL查询本身中执行此操作,或者我只需要执行此操作

SELECT * FROM ToursCartsItems WHERE UserId IN ("old", "new")

然后自己在PHP中进行必要的计算?

2 个答案:

答案 0 :(得分:0)

我可能错了,但这听起来像是购物车情景。为什么不在单独的表中存储匿名和登录的游览?即,在用户登录后,将匿名的“购物车”游览转换为另一个表中的实际游览“订单”?

这样你就不会破坏任何数据。此外,您如何知道刚登录的人与登录前加入游览的人相同?

答案 1 :(得分:0)

我想你要做的是首先删除冲突的记录,然后插入新记录。这可能会有所帮助......

mysql> select * from ToursCartsItems;
+----+--------+--------+-----------+
| Id | UserId | TourId | CreatedAt |
+----+--------+--------+-----------+
|  1 | old    |      1 |      NULL | 
|  2 | old    |      2 |      NULL | 
|  3 | new    |      1 |      NULL | 
|  4 | new    |      3 |      NULL | 
+----+--------+--------+-----------+
4 rows in set (0.00 sec)

mysql> delete from b using ToursCartsItems as a inner join ToursCartsItems as b on a.TourId = b.TourId where a.UserId = 'new' and b.UserId = 'old' and a.Id <> b.Id;

mysql> select * from ToursCartsItems;
+----+--------+--------+-----------+
| Id | UserId | TourId | CreatedAt |
+----+--------+--------+-----------+
|  2 | old    |      2 |      NULL | 
|  3 | new    |      1 |      NULL | 
|  4 | new    |      3 |      NULL | 
+----+--------+--------+-----------+
3 rows in set (0.00 sec)