2014-12-28 109 views
2

我有一个mysql查询的问题。SQL INSERT WITH JOIN

这是我的2个表:

player_locations:

ID | playerid | type | location 
---|----------------------- 

users:

ID | playername | [..] 
----|-------------------- 
1 | example1 | ... 

我要插入player_locations如下:

ID | playerid | type | location 
---|----------------------- 
1 |  1  | 5 | DOWNTOWN 

而这就是我的查询:

INSERT INTO player_locations (id, type, location) 
    SELECT u1.ID as playerid, 
     d.type, 
     d2.location 
    FROM users u1 
    INNER JOIN users u2 
    ON 1 = 1 
    INNER JOIN (SELECT 5 as type 
     FROM DUAL) d 
    INNER JOIN (SELECT "DOWNTOWN" as location 
     FROM DUAL) d2 
    ON 1 = 1 
    WHERE u1.playername = "example1"; 

但是,当我在users有6排它player_locations

+0

你的问题与'java'(标记删除)有什么关系? – Pshemo

+0

我将在java中使用查询。我想我应该提到它。 – magl1te

回答

0

为什么不直接写这个?

INSERT INTO player_locations(id, type, location) 
    SELECT u.ID as playerid, 5 as type, 'DOWNTOWN' as location 
    FROM users u 
    WHERE u.playername = 'example1'; 

自连接没有任何意义。您在查询中没有使用来自u2的任何信息,因此它只是乘以行数。额外的常量连接是不必要的。

+0

就是这样。谢谢! – magl1te

0

插件6个相同的行以WHERE子句出来,把你的选择中在插入的()和那应该为你做。

+0

我需要WHERE子句,因为我必须在WHERE子句中获得playername的ID – magl1te

+0

Isnt在选择语句开始时消耗的ID是多少?如果你想让它从[user]下的所有行中获得id,那么你将不得不删除where,否则它会用[select]返回的单个结果填充[player_location]。 – user2975403