MySQL 条件插入。适用于 phpMyAdmin 但不适用于 PHP 脚本
我正在尝试从 PHP 脚本创建一个条件 INSERT 到我的 MySQL 数据库中。以下 SQL 语法适用于 phpMyAdmin,但不适用于我的 PHP 脚本:(
INSERT INTO profiles (id, firstname)
SELECT "22","John" from profiles
WHERE NOT EXISTS (
SELECT * FROM li_profiles
WHERE li_p_firstname = "John"
)
请注意,“id”是主键,“firstname”不是键或唯一)
可能是问题的一部分的奇怪之处是,当我运行当 phpMyAdmin 中的 SQL 确实“工作”(意味着添加了 id“22”和名字“John”的新记录)时,我收到以下警告:“#1062 - 键 1 的重复条目“22” ” 但表中没有 id 为 22 的先前条目。??!!
这是怎么回事?
I am trying to create a conditional INSERT into my MySQL databate from a PHP script. The following SQL syntax works in phpMyAdmin, but not in my PHP Script:
INSERT INTO profiles (id, firstname)
SELECT "22","John" from profiles
WHERE NOT EXISTS (
SELECT * FROM li_profiles
WHERE li_p_firstname = "John"
)
(Note that "id" is the primary key, "firstname" is not a key or unique)
Something weird that might be part of the issue is that when I run that SQL in phpMyAdmin, while it does "work" (meaning that a new record is added with the id "22" and the firstname "John") I get the following warning: "#1062 - Duplicate entry '22' for key 1"
But the table didn't have a previous entry with id of 22. ??!!
What's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 SELECT 更改为 VALUES
此外,如果您使用自动增量值,则应指定下一个值。另外,如果它是整数,请给出整数 (22) 而不是字符串 ("22")
Change SELECT to VALUES
Also, if you are using auto-increment values, you should specify the next value. Also, if its an integer, give an integer (22) not a string ("22")
您将获得 iD 的重复条目,因为您要为
profiles
表中的每一行插入一个新行;对于profiles
表中的每一行,li_profiles
表中都没有 John。您可以尝试消除重复的问题(如果有效,抱歉,但我自己没有检查过)。
You'll get a duplicate entry for the iD because you are inserting a new row for each row in the
profiles
table; for every row in theprofiles
table there is no John in theli_profiles
table. You might trywhich would eliminate the duplicate problem (if it works, sorry but I haven't checked this myself).
我以不同的方式解决了这个问题。 (我被告知 HAVING 语句很慢,所以我不确定这是最好的方法......但它是我可以工作的唯一方法。)
I figured it out in a different way. (I'm told that the HAVING statement is slow, so I'm not sure that it's the best way... but it the only method I've gotten to work.)