0

我的代码有语法错误

$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

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

有什么帮助吗?

4

3 回答 3

3

你错过了FROM第一个 SELECT

SELECT '$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id'
# MISSED HERE FROM ???
WHERE NOT EXISTS
于 2012-10-11T22:10:15.180 回答
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;

结果

于 2012-10-11T22:27:14.860 回答
0

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

$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关键字告诉它什么都不做。

于 2012-10-11T23:12:10.677 回答