简体   繁体   中英

MySQL select in update statement

This MySQL statement give me all id_duel_player for player with id_player=30 and it work fine.

SELECT   b.id_duel_player
FROM    duels a                            
        INNER JOIN duel_player b          
            ON a.id_duel = b.id_duel
WHERE   id_player = 30 
UNION ALL
SELECT  c.id_duel_player
FROM    duel_player c
        INNER JOIN
        (
            SELECT  aa.*
            FROM    duels aa
                    INNER JOIN duel_player bb
                        ON aa.id_duel = bb.id_duel
            WHERE   bb.id_player = 30
        ) d ON c.id_duel = d.id_duel AND c.id_player <> 30

I want to make MySQL statement for UPDATE (fields from duel_player table) all of this id_duel_player that returns this select statement.

UPDATE duel_player
SET num = 2,
    total = 5
WHERE (duel_player.id_duel_player = id_duel_player's from above SELECT statement)

I want most effective and fastest way to do this.

Thanks

For 200-400 rows it's likely fastest to create a temporary table with the results, and then do the UPDATE with a join:

CREATE TEMPORARY TABLE id_duel_players AS
SELECT b.id_duel_player as id FROM duels a ...

UPDATE duel_player
JOIN id_duel_players ON duel_player.id_duel_player = id_duel_players.id
SET num = 2,
    total = 5

For smaller result sets you may find the IN operator sufficiently fast ( ... WHERE id_duel_player IN (SELECT ...) ), but I've found it unreliable for result sets with hundreds of rows. (Unreliable = suddenly no matches are found, no idea why, I haven't investigated.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM