INSERT ... WHERE NOT EXISTS错误

时间:2012-10-11 22:06:34

标签: php mysql

我的代码出现语法错误

$insert = @mysql_query("INSERT INTO topics (t_title, t_desc, t_pic, t_link, t_date,cat_id)
SELECT '$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id'
WHERE NOT EXISTS (SELECT t_link
FROM topics
WHERE t_link = $t_link
) 
")or die(mysql_error());

这会返回错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT t_link FROM topics WHERE t_link = 'showthread.php?t=120' at line 3

我认为问题在于t_link = $ t_link

但是当我用正常值替换它时,问题仍然存在。

有任何帮助吗?

3 个答案:

答案 0 :(得分:3)

您在第一次选择

时错过了FROM
SELECT '$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id'
# MISSED HERE FROM ???
WHERE NOT EXISTS

答案 1 :(得分:1)

这里解决FROM CLAUSE,请检查解决方案chumkiu的答案,而不是我的。

create table a ( i int);

insert into a (i )
select 1
from dual
where 1=2;

insert into a (i )
select 3
from dual
where 1=1;

Results

答案 2 :(得分:0)

如果t_link在表格中有唯一索引,您可以执行以下操作:

$insert = @mysql_query("INSERT IGNORE INTO topics (t_title, t_desc, t_pic, t_link, t_date,cat_id)
    VALUES ('$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id');

IGNORE关键字表示如果插入将复制唯一键约束,则不执行任何操作。

相关问题