假设我有一个包含
信息的表格game (PRIMARY INT id, TINYINT offline)
以及第二张表格,其中包含有关该游戏的详细信息:
gamedetail (PRIMARY INT id, INT game_id (fk to game table), TINYINT offline)
详细信息会经常更新并从各种程序中更新。在那里我设置了细节的离线标志。我没有编程设置游戏本身的离线标志的可能性。 (我确实将游戏的离线标志设置为0,但是,如果我找到在线详细信息)。但我想通过更新查询在数据库中设置此信息。这个想法就是这个SELECT:
SELECT DISTINCT game.id FROM game
LEFT JOIN gamedetail AS gdon
ON (gdon.game_id = game.id AND gdon.offline = 0)
LEFT JOIN gamedetail AS gdoff
ON (gdoff.game_id = game.id AND gdoff.offline = 1)
WHERE gdoff.id IS NOT NULL AND gdon.id IS NULL;
这给了我很好的所有游戏,我只有离线游戏细节。所以我想将此作为UPDATE语句的输入,如下所示:
UPDATE game SET game.offline=1 WHERE game id IN (
SELECT DISTINCT game.id FROM game
LEFT JOIN gamedetail AS gdon
ON (gdon.game_id = game.id AND gdon.offline = 0)
LEFT JOIN gamedetail AS gdoff
ON (gdoff.game_id = game.id AND gdoff.offline = 1)
WHERE gdoff.id IS NOT NULL AND gdon.id IS NULL;
)
由于ERROR 1093 (HY000): Table 'game' is specified twice, both as a target for 'UPDATE' and as a separate source for data
,这很遗憾在mysql中失败。
我的问题是如何将我的更新语句更改为适用于mysql的内容?
编辑:更正了WHERE条件
答案 0 :(得分:8)
将查询包装在子查询中,如下所示:
UPDATE game SET game.offline=1 WHERE game.id IN (
SELECT * FROM (
SELECT DISTINCT game.id FROM game
LEFT JOIN gamedetail AS gdon
ON (gdon.game_id = game.id AND gdon.offline = 0)
LEFT JOIN gamedetail AS gdoff
ON (gdoff.game_id = game.id AND gdoff.offline = 1)
WHERE gdon.id IS NOT NULL AND gdon.id IS NULL;
) t
)
答案 1 :(得分:2)
只需使用简单的连接,无需使用子查询
UPDATE game
LEFT JOIN gamedetail AS gdon
ON (gdon.game_id = game.id AND gdon.offline = 0)
LEFT JOIN gamedetail AS gdoff
ON (gdoff.game_id = game.id AND gdoff.offline = 1)
SET game.offline=1
WHERE gdoff.id IS NOT NULL AND gdon .id IS NULL;
或者,如果您使用子查询,则需要提供一个新别名,因为在更新查询中您可以在where子句中指定相同的表,我猜其中where条件应为WHERE gdoff.id IS NOT NULL AND gdon .id IS NULL