“如果不存在”SQL语句给出错误

时间:2014-03-10 00:24:46

标签: mysql sql database

我运行了以下sql查询,它给出了错误1064,语法错误。

IF NOT EXISTS (select * from locations where STREET_ADDRESS = 'test') 
BEGIN
    insert into locations (STREET_ADDRESS) values ('test') 
end;

有人可以帮帮我吗?它似乎很简单但它不会运行。感谢。

另外,我正在运行MySQL 5.6.11版本

3 个答案:

答案 0 :(得分:0)

你也可以试试这个

INSERT INTO locations (STREET_ADDRESS)
SELECT 'test' FROM DUAL
WHERE NOT EXISTS (
   SELECT * from locations where STREET_ADDRESS = 'test'
) LIMIT 1;

答案 1 :(得分:0)

试试这个

IF ((select * from locations where STREET_ADDRESS = 'test')=0 )
BEGIN
insert into locations (STREET_ADDRESS) values ('test') 
end;

答案 2 :(得分:0)

你应该使用这种类型的示例代码:

   INSERT INTO table_listnames (name, address, tele)
    SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
    WHERE NOT EXISTS (
        SELECT name FROM table_listnames WHERE name = 'Rupert'
    ) LIMIT 1;

click here