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)
ajreal
  • 46,720
  • 11
  • 89
  • 119
Nilks
  • 446
  • 4
  • 14
  • dup : http://stackoverflow.com/questions/913841/mysql-conditional-insert – Haim Evgi Dec 05 '10 at 12:30
  • I've seen that and tried that (as you would have known if you actually saw my code). It doesn't work. Not for me atleast. – Nilks Dec 05 '10 at 13:03

1 Answers1

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;
ajreal
  • 46,720
  • 11
  • 89
  • 119