我有两张桌子 - “活动”和“房间”。
房间表如下:
CREATE TABLE `rooms` (
`roomKey` INT(9) UNSIGNED NOT NULL AUTO_INCREMENT,
`locationID` INT(9) NOT NULL DEFAULT '0',
`locationName` VARCHAR(150) NOT NULL DEFAULT '',
`buildingID` INT(9) NOT NULL DEFAULT '0',
`buildingName` VARCHAR(150) NOT NULL DEFAULT '',
`areaID` INT(9) NOT NULL DEFAULT '0',
`areaName` VARCHAR(150) NOT NULL DEFAULT '',
`roomID` INT(9) NOT NULL DEFAULT '0',
`roomName` VARCHAR(150) NOT NULL DEFAULT '',
`clientKey` MEDIUMINT(5) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`roomKey`),
UNIQUE INDEX `locationID` (`locationID`, `buildingID`, `areaID`, `roomID`, `clientKey`),
INDEX `clientKey` (`clientKey`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=21270411;
并且事件表如下所示:
CREATE TABLE `events` (
`eventKey` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`accountNum` INT(11) NULL DEFAULT NULL,
`locationID` INT(9) NOT NULL DEFAULT '0',
`buildingID` INT(9) NOT NULL DEFAULT '0',
`areaID` INT(9) NOT NULL DEFAULT '0',
`roomID` INT(9) NOT NULL DEFAULT '0',
`clientKey` SMALLINT(5) UNSIGNED NOT NULL,
`roomKey` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`eventTitle` VARCHAR(100) NOT NULL DEFAULT '',
`dateStart` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
`dateEnd` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`eventKey`),
UNIQUE INDEX `uniqueEvent` (`accountNum`, `locationID`, `buildingID`, `areaID`, `roomID`),
INDEX `clientKey` (`clientKey`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=98690419;
有一个过程会将新事件的批量导入插入到事件表中。一旦完成,我们需要使用与“rooms”表中的主键对应的roomKey更新新记录 - 我们可以使用房间中记录的locationID,buildingID,areaID,roomID和clientKey来匹配表。 (clientKey是必要的,因为多个帐户可以具有相同的位置,bldg,区域或房间值。)
目前,我使用的查询是:
UPDATE events e, rooms dr SET e.locationKey=dr.locationKey
WHERE e.locationID=dr.locationID
AND e.buildingID=dr.buildingID
AND e.areaID=dr.areaID
AND e.roomID=dr.roomID
AND e.clientKey=dr.clientKey
但它没有考虑两个帐户(客户)在location,bldg,area和room中具有相同值的情况。根据另一个帐户具有相同locationID,buildingID,areaID和roomID的房间记录这一事实,查询很容易将错误的roomKey值放入事件记录中。
我可以将查询修改为如下所示运行,但速度非常慢。我知道这不是正确的查询,因此我希望改进它 - 无需使用PHP循环等进行此更新。
UPDATE EVENTS e, rooms dr SET e.locationKey=dr.locationKey
WHERE (e.locationID=dr.locationID AND e.clientKey=dr.clientKey)
AND (e.buildingID=dr.buildingID AND e.clientKey=dr.clientKey)
AND (e.areaID=dr.areaID AND e.clientKey=dr.clientKey)
AND (e.roomID=dr.roomID AND e.clientKey=dr.clientKey)
AND e.clientKey=dr.clientKey
答案 0 :(得分:0)
在Mysql中,您可以在加入update
UPDATE table1 t1
INNER JOIN table2 t2
ON t1.id = t2.id
SET t1.col1 = t2.col2, t1.col2 = t2.col2
答案 1 :(得分:0)
如果clientKey
中的rooms
值具有权威性,您只想根据匹配的clientKey
值更新events
中的所有roomID
值,那么您应该能够做到这一点:
UPDATE rooms AS r
INNER JOIN events AS e ON r.roomKey = e.roomKey
SET e.clientKey = r.clientKey