0

I'm trying to insert a row into a table, but only if the combination of the X and Y does not exist in the table already, so I searched around and eventually came up with this query, but it's doing nothing, and throwing no errors.

INSERT INTO `tiles` (`TileID`, `Type`, `X`, `Y`) 
 SELECT UUID(), (FLOOR(RAND() * 4)), 0, 0 FROM `tiles` 
 WHERE NOT EXISTS (SELECT 1 FROM `tiles` WHERE `X`=0 AND `Y`=0) LIMIT 1;

Any help is greatly appreciated.

2
  • Possible duplicate of stackoverflow.com/questions/3164505/… Commented Jul 21, 2013 at 3:19
  • ang how is you outer select connected with the select on exists block? Commented Jul 21, 2013 at 3:37

2 Answers 2

1

A possible solution might be to add a UNIQUE constraint on (x, y)

ALTER TABLE tiles ADD UNIQUE (x, y);

and use INSERT IGNORE

INSERT IGNORE INTO tiles VALUES (UUID(), (FLOOR(RAND() * 4)), 0, 0);
INSERT IGNORE INTO tiles VALUES (UUID(), (FLOOR(RAND() * 4)), 0, 0);

Here is SQLFiddle demo

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

Comments

1

Essentially, all you have to do it wrap your select with select * from(). This makes your query:

INSERT INTO `tiles` (`TileID`, `Type`, `X`, `Y`) 
SELECT * FROM (SELECT UUID(), (FLOOR(RAND() * 4)), 0 as x, 0 as y) as tmp
WHERE NOT EXISTS (SELECT 1 FROM `tiles` WHERE `X`=0 AND `Y`=0) LIMIT 1;

I had to add the "as x" and "as y" because mysql was complaining about "duplicate column name '0'". My guess is that without the name explicitly written out it just uses the value as the name. Anyway, this query should work. Also, there is more information about this type of stuff in Kyle's link above.

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.