SQL INSERT WITH JOIN

时间:2014-12-28 19:17:49

标签: mysql join insert rows

我遇到mysql查询问题。

这是我的两张桌子:

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

中插入6行相同的行

2 个答案:

答案 0 :(得分:0)

取出WHERE子句,将你的选择放在插入的()中,并且应该为你做。

答案 1 :(得分: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中的任何信息,因此它只是将行数相乘。常量的额外连接是不必要的。