简体   繁体   中英

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

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));

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM