3

I am busy doing an UPDATE/INSERT request, but here is the crux:

table PLAYERS {
    player_id
    game_id
    team_id
    position
    number
}

What is supposed to happen is the following:

I test if there is an entry where player_id = '$player_id' AND game_id = '$game_id' AND team_id = '$team_id'.

If there is, then the following happens:

position = '$position' AND number = '$number'

Is there any way I can do this using just MySQL query language, without the need for PHP validation between queries?

2
  • I don't have a PRIMARY KEY for this table, but have INDEXES on game_id, player_id, and team_id, if that helps... Commented Aug 20, 2009 at 22:35
  • You can create a compound Primary Key across the game, player and team fields. Commented Aug 20, 2009 at 22:52

3 Answers 3

6
INSERT INTO TABLE (COLUMNS) VALUES(FIELDS) UPDATE ON DUPLICATE KEY position = somevalue, number=number

1) Tries to Insert
2) If there is a record with a unique field (Primary Key, Unique Index, etc) update that field instead.

Sign up to request clarification or add additional context in comments.

6 Comments

This is my query: INSERT INTO players (game_id,player_id,position,number) VALUES('$game_id','$players[$i]','$position[$i]','$number') UPDATE ON DUPLICATE KEY position = '$position[$i]', number='$number' But I get the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE ON DUPLICATE KEY position = 'LH Prop', number='1'' at line 1 Any ideas?
I have been inserting like this the whole time, and it worked.
I think it should be "ON DUPLICATE KEY UPDATE"
Yes, thanks Zed, I changed it to that and then it processed, but I think my problem is the fact that I don't have any PRIMARY KEY, except INDEXES on game_id, player_id and team_id. So it processes the request, but keeps on inserting new entries, but in fact, the new entries are precise duplicates of other entries in the table. Anyone else have some direction for me?
ALTER TABLE PLAYERS ADD PRIMARY KEY (player_id, game_id, team_id);
|
0

Well, I fixed this with multiple IF-statements to determine whether to insert or to update.

Comments

0

That will not work unless its in a transaction, or you can guarantee that simultaneous requests against the DB will not be run

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.