MySQL Conditional INSERT

2019-02-28 22:39发布

问题:

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)

回答1:

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;