表格如下:
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 字段是 a 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 中进行必要的计算?