Insert Into table If similar value exists in another existing table (not a foreign key)

故事扮演 提交于 2019-12-24 23:11:10

问题


I'm trying to insert an "Item order" in a table called AsksFor and I want to make sure the Item and ItemManufacturer exists in the table Sells. However I keep getting "syntax error, unexpected if, expecting END_OF_INPUT or ';'" for using the IF. Anyone know any other ways to write this for MySQL?

INSERT INTO AsksFor (Username, ItemName, ItemManufacturer)
VALUES ('Harish', 'zkoxtlv93', 'tbzrt93')
IF EXISTS(SELECT ItemName, ItemManufacturer
        FROM Sells
        WHERE Sells.ItemName = VALUES(ItemName)
        AND Sells.ItemManufacturer = VALUES(ItemManufacturer));

回答1:


EXISTS clause is not availaible for MySQL . Anyways you don't need it , the AND condition in WHERE clause performs the checking part whether values exists in source table Sells.

Try this

INSERT INTO AsksFor (Username, ItemName, ItemManufacturer)
SELECT DISTINCT 'Harish',ItemName, ItemManufacturer
        FROM Sells
        WHERE ItemName='zkoxtlv93' AND ItemManufacturer='tbzrt93'


来源:https://stackoverflow.com/questions/22926726/insert-into-table-if-similar-value-exists-in-another-existing-table-not-a-forei

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