问题描述
我建立一个计数器。我有一篇文章目录和跟踪访问者。当访问者来到我插入文章ID并在数据库中的IP地址。首先,我检查,看看是否存在知识产权的文章编号,如果IP不存在我做的插入。这是两个查询 - 有没有办法让这个一个查询
I am building a hit counter. I have an article directory and tracking unique visitors. When a visitor comes i insert the article id and their IP address in the database. First I check to see if the ip exists for the article id, if the ip does not exist I make the insert. This is two queries -- is there a way to make this one query
另外,我不使用我经常使用内联SQL存储过程
Also, I am not using stored procedures I am using regular inline sql
推荐答案
这里有一些选择:
INSERT IGNORE INTO `yourTable`
SET `yourField` = 'yourValue',
`yourOtherField` = 'yourOtherValue';
这是MySQL参考手册:如果你使用ignore关键字,在执行INSERT语句中出现的错误作为警告处理来代替。例如,如果没有理睬,说复制表中现有的唯一索引或主键值的行时,会导致重复键错误和声明被中止。)如果记录不存在,它会创建
from MySQL reference manual: "If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted.".) If the record doesn't yet exist, it will be created.
另一种选择是:
INSERT INTO yourTable (yourfield,yourOtherField) VALUES ('yourValue','yourOtherValue')
ON DUPLICATE KEY UPDATE yourField = yourField;
不会引发错误或警告。
Doesn't throw error or warning.
这篇关于插入行仅如果行不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!