1

I want to do a conditional insert with MySQL. I have 2 tables (Car and CarType).

The Car table got a coloumn called typeId, which points to an entry in the CarType table.

I only want to insert a row in the Car table if the given typeId exists in the CarType table.

I've tried some Googling, and tried a couple of solutions. Here is what I found
(but it does not work):

INSERT INTO Car (title, licensePlate, carType 
SELECT 'Ford Transit', 'SV 32 654', '13' 
FROM DUAL 
    WHERE EXISTS (SELECT typeId FROM CarType WHERE typeId = 13)
2

1 Answer 1

3

I think you misleading by the example, it can be as simple as this :

INSERT INTO Car (title, licensePlate, carType) 
  SELECT 'Ford Transit', 'SV 32 654', '13' 
  FROM CarType WHERE typeId=13;
Sign up to request clarification or add additional context in comments.

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.