MySQL REPLACE 行,其中字段 a 等于 x,字段 b 等于 y
我正在尝试构建一个“新评论”功能,向用户显示自上次访问以来的新评论数量。 我构建了一个“视图”表,其中包含主题 ID、用户 ID 和时间戳。每次用户访问该主题时更新时间戳或插入新行(如果不存在)的最佳方法是什么?目前我有:
REPLACE INTO Views (MemberID, TopicID, Visited)
SET ('$_SESSION[SESS_MEMBER_ID]', '$threadid', '$t')
WHERE MemberID = $_SESSION[SESS_MEMBER_ID] AND TopicID = $threadid
但是,这不起作用。是否可以在一个查询中完成此操作?
I'm trying to construct a 'new comments' feature where the user is shown the number of new comments since the last visit.
I've constructed a 'Views' table that contains the topic id, the user id and a timestamp. What's the best way of updating the timestamp every time the user visits that topic or inserting a fresh row if one doesn't exist? At the moment I have:
REPLACE INTO Views (MemberID, TopicID, Visited)
SET ('$_SESSION[SESS_MEMBER_ID]', '$threadid', '$t')
WHERE MemberID = $_SESSION[SESS_MEMBER_ID] AND TopicID = $threadid
However, this does not work. Is it possible to do this in one query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将
SET
替换为VALUES
。语法为:编辑: 请注意,只有当您将
MemberID
和TopicID
设置为表中的唯一键时,这才真正有效。如果你这样做,那么你应该能够执行以下任一操作:或者
(当然,你应该使用正确的占位符,这样 Little Bobby Tables 就不会访问并破坏你的数据库)
Try replacing
SET
withVALUES
. The syntax is:Edit: Note that this only really works if you have set
MemberID
andTopicID
as a unique key in your table. If you do this, then you should just be able to do either:or
(of course, you should be using proper placeholders so Little Bobby Tables doesn't make a visit and destroy your database)
我想不出一种只有一个查询的方法,但你可以尝试这个:
这将总共运行两个查询。
I can't think of a way with only one query, but you could try this:
That would run two queries total.
如果您使用
TIMESTAMP
数据类型,则每次更改行时它都会自动更新。因此,只需对该行调用 update(如果存在,否则创建它)并仅更改 topicId。数据库将处理时间的更改。真的,我不会使用 REPLACE。相反,也许您可以创建一个存储过程来检查该行是否存在(只需传递 memberId 和 topicId),如果不存在则创建它,然后将时间戳返回给您。这更有意义。
使用存储过程意味着只需访问一次数据库。
If you're using the
TIMESTAMP
data type, it will update itself automatically every time the row is altered. So just call update on the row (if it exists, otherwise create it) and change just the topicId. The database will handle changing the time.Really, I wouldn't use REPLACE. Instead, maybe you could create a stored procedure that checks to see if the row exists (just pass the memberId and topicId) and creates it if not, and then returns the timestamp to you. This makes more sense.
And using a stored proc means only one trip to the DB.