MySQL Conditional INSERT

南楼画角 提交于 2019-12-02 13:12:15

问题


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;


来源:https://stackoverflow.com/questions/4358730/mysql-conditional-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!