如何自动限制数据库的行数?
我有下表,
+-----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+----------------+
| ID | int(11) unsigned | NO | PRI | NULL | auto_increment |
| userid | int(10) unsigned | NO | MUL | NULL | |
| logintime | int(10) unsigned | NO | | NULL | |
| loginIP | int(4) unsigned | NO | | NULL | |
+-----------+------------------+------+-----+---------+----------------+
每次用户登录时,我都会在该表中插入一个新行,其中包含他们的登录时间、IP 地址等...
现在我想将行数限制为每个用户仅 10 行!即,如果用户 ID 5 已经有 10 行,并且我要插入新行,那么我需要在插入之前删除其中最旧的一行。
有没有办法编写一个 SQL 语句来DELETE
删除某个用户 ID 的所有条目(最近 10 个条目除外)。我知道如何对 SELECT
使用 LIMIT
,但我不知道如何在 DELETE
中实现 LIMIT。
I have the following table
+-----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+----------------+
| ID | int(11) unsigned | NO | PRI | NULL | auto_increment |
| userid | int(10) unsigned | NO | MUL | NULL | |
| logintime | int(10) unsigned | NO | | NULL | |
| loginIP | int(4) unsigned | NO | | NULL | |
+-----------+------------------+------+-----+---------+----------------+
I insert a new row in this table every time a user logs in, which contains their login time, IP address etc...
Now I want to limit the number of rows to only 10 per user! i.e. if there's 10 rows for userid 5, already and I'm inserting a new one, I need to delete the oldest one of them before the insert.
is there a way to write a SQL statement that DELETE
s all entries of a userid, except for the recent 10 ones. I know how to use LIMIT
for a SELECT
, but I cannot see how I can implement the LIMIT in a DELETE
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按照这些思路应该可以工作:
-- 补充:其中 userID = xyz
Something along these lines should work:
-- added: where userID = xyz