MySql 更新具有 X 和 Y 的第一个条目,否则插入新记录
我在 MySql 表中有一个聊天用户条目 -
id(主键,自动增量) - 聊天用户 id
user_id - 与我们的产品相关的用户 ID
room_id - 您所在房间的 ID
如果聊天操作员进入房间,离开,然后回来 - 就像现在一样 - 将在房间中创建两个条目(插入聊天用户...)
我知道如果不存在则插入语法,但是我想要 IF NOT EXISTS 不在主键上,而是在 WHERE user_id = x AND room_id = y (如果他们重新进入他们曾经所在的房间,这将是相同的)
类似 INSERT INTO chatuser SET user_id=4, room_id=2 IF 条目不存在且已包含这些值;)
谢谢
I have a chat user entry in a MySql table -
id (primary key, autoincrement) - the chat user id
user_id - the users id as it pertains to our product
room_id - the id of the room your in
If a chat operator enters the room, leaves, and then comes back - as it is now - will create two entries in the room (INSERT INTO chatuser ...)
I know INSERT IF NOT EXISTS syntax, however I want to IF NOT EXISTS not on the primary key, but WHERE user_id = x AND room_id = y (which will be the same if they re-enter a room they have been in)
something like INSERT INTO chatuser SET user_id=4, room_id=2 IF ENTRY DOESNT EXIST WITH THOSE VALUES ALREADY ;)
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在 (user_id,room_id) 上有唯一索引,则可以执行
INSERT ... ON DUPLICATE KEY UPDATE
(如果不需要更新,则可以执行INSERT IGNORE
当记录已经存在时的任何内容):If you have a unique index on (user_id,room_id), you can do
INSERT ... ON DUPLICATE KEY UPDATE
(orINSERT IGNORE
if you don't need to update anything when the record already exists):我认为我们这里遇到的是设计问题。您有 3 个表:一个用户表、一个房间表和一个链接这两个表的表。最后一个是我们正在处理的。现在,如果您想在每次用户进入房间时进行记录,那么您拥有的表格设计是理想的选择。然而,这似乎不是你正在做的。看来您只想要最后一次访问的条目。在这种情况下,您的表不应具有自动递增主键,而应将 userID 和 roomID 都作为多列主键的一部分。
将表修改为该设置,然后使用
ON DUPLICATE KEY UPDATE
子句运行插入语句。I think what we have here is a design issue. You have 3 tables, a user table, a room table and a table that links that two. The last one is what we're working with here. Now, if you want to log every time a user enters a room, the table design you have is ideal. However it seems that is not what you are doing. It seems you want an entry for just the last visit. In this case your table should not have an auto incrementing primary key, and instead should have userID and roomID to both be parts of a multi-column primary key.
Modify your table to that set-up then run your insert statement with
ON DUPLICATE KEY UPDATE
clause.