更新今天日期的记录是否已存在
是否有一种简单的方法可以更改以下查询,以检查今天日期是否已存在记录(如果确实存在),并使用最新的计数值对其进行更新。
mysql_query("INSERT INTO daily_record (PageID, count)
VALUES (".$array['page_id'].",".$array['count'].")");
我想要检查的列是 CURRENT_TIMESTAMP 字段(record_date - daily_record 表的一部分),如果 pageID 存在今天的日期,则需要进行更新而不是新插入。
如果有人可以提供帮助那就太棒了!
Is there is an easy way to change the following query to check to see if a record already exists for todays date if it does to update it with the newest count value.
mysql_query("INSERT INTO daily_record (PageID, count)
VALUES (".$array['page_id'].",".$array['count'].")");
The column I want to check is a CURRENT_TIMESTAMP
field (record_date - part of daily_record table) if a todays date exists for a pageID then an update needs to happen rather than a new insert.
If someone can help that would be amazing!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,如果您像这样构建
daily_record
表:然后您可以使用以下命令:
显然 pageID/record_date/count 将由调用代码提供。这将有效地为具有给定计数的 pageID/天创建一条记录,或者如果 pageID/天的记录已存在,则它将计数设置为提供的值。
使用 DATE 列类型可以防止您获得免费时间戳,但这对于该表来说并不是特别有用 - 您描述它的方式 - 因为您不关心小时/分钟/秒。
这里的键是由
PRIMARY KEY...
行创建的唯一索引。如果插入会破坏它的唯一性,则可以对其进行更新。Well if you build the
daily_record
table like this:You could then use the command:
Obviously pageID/record_date/count would be supplied by the calling code. This effectively creates a record for the pageID/day with the given count, or if a record for the pageID/day already exists, then it sets the count to the supplied value.
Using the DATE column type prevents you getting free timestamping BUT that's not particularly useful for this table - the way you describe it - since you don't care about the hours/minutes/seconds.
The key here is the unique index created by the
PRIMARY KEY...
line. If it's uniqueness would be violated by an insert then an update on it can occur instead.我能想到的最好办法是使用
select
和if ... then
提前检查是否存在,或者运行update
> 语句首先,检查@@rowcount
(受影响的记录),如果返回 0,则执行insert
),即否。
Best I can come up with is either use a
select
withif ... then
to check for the existance ahead of time, or run theupdate
statement first, check@@rowcount
(records affected) and do aninsert
if it comes back with 0)i.e. No.
[编辑 - 由于日期的原因,这比一开始看起来要复杂一些。]
要更新记录,您必须获取要更新的计数,因此需要您首先使用 SELECT。但您需要选择仅当前日期的记录。
假设您已经完成了将当前日期放入 $today 的代码。
然后正如肯德里克所说,
[Edit - this is a little more complex than it seemed at first, because of the DATE thing.]
To UPDATE the record you MUST get the count that you want to update, so that requires you to use a SELECT first. But you need to select the records that are only for the current date.
Let's assume that you have done the code to get the current date into $today.
Then as Kendrick said,