2014-12-28 142 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