使用两个表

时间:2016-07-06 22:46:00

标签: mysql sql

我正在尝试进行查询,以避免使用太多的PHP。我想通过在表格升级中添加这些值来更新 world1 的行(木材,小麦,黄金,肉类)。这是我能得到的:

SELECT wood_cancel, wheat_cancel, gold_cancel, meat_cancel FROM upgrading WHERE world = 'world1' AND player_id = 190 AND city_id = 1 AND cancel_id = 'cancel_wood_rate_1';
UPDATE world1 SET wood = wood + wood_cancel, wheat = wheat + wheat_cancel, gold = gold + gold_cancel, meat = meat + meat_cancel WHERE player_id = 190 AND city_id = 1;
DELETE FROM upgrading WHERE world = 'world1' AND player_id = 190 AND city_id = 1 AND cancel_id = 'cancel_wood_rate_1'SELECT wood_cancel, wheat_cancel, gold_cancel, meat_cancel FROM upgrading WHERE world = 'world1' AND player_id = 190 AND city_id = 1 AND cancel_id = 'cancel_wood_rate_1';

SQL错误消息说无法找到wood_cancel,wheat_cancel,gold_cancel和meat_cancel。我该怎么办?

我需要使用某种JOIN吗?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:1)

你可以使用JOIN进行UPDATE,其语法与在执行JOIN时类似,如下所示:

UPDATE world1 w INNER JOIN upgrading u 
ON w.player_id = u.player_id AND w.city_id = u.city_id
SET w.wood = w.wood + u.wood_cancel
WHERE u.world = 'world1' AND u.player_id = 190
AND u.city_id = 1 AND u.cancel_id = 'cancel_wood_rate_1';

DELETE FROM upgrading 
WHERE world = 'world1' AND player_id = 190 
AND city_id = 1 AND cancel_id = 'cancel_wood_rate_1';

http://sqlfiddle.com/#!9/242f8/2

答案 1 :(得分:0)

发生此错误的原因是因为来自一个语句的值不会转移到没有JOIN或类似的其他语句。即MySQL不理解wood_cancel来自之前的SELECT语句。

MySQL确实有user-defined variables的概念。使用这种类型的方法,您只需在开头插入PHP中的值。

就个人而言,我会将所有逻辑转移到PHP中,以便在数据库级别不会出现逻辑。

注意:未经测试。

SET @world = 'world1'
    @player_id = 190, 
    @city_id = 1, 
    @cancel_id = 'cancel_wood_rate_1',
    @wood_cancel = 0,
    @wheat_cancel = 0,
    @gold_cancel = 0,
    @meat_cancel = 0

SELECT 
    @wood_cancel := wood_cancel, @wheat_cancel := wheat_cancel, @gold_cancel := gold_cancel, @meat_cancel := meat_cancel
FROM 
    upgrading 
WHERE 
    world = @world
AND player_id = @player_id 
AND city_id = @city_id
AND cancel_id = @cancel_id;

UPDATE 
    world1 
SET 
    wood = wood + @wood_cancel, 
    wheat = wheat + @wheat_cancel, 
    gold = gold + @gold_cancel, 
    meat = meat + @meat_cancel 
WHERE 
    player_id = @player_id 
AND city_id = @city_id;

DELETE FROM 
    upgrading 
WHERE 
    world = @world 
AND player_id = @player_id 
AND city_id = @city_id
AND cancel_id = @cancel_id;