如何自动限制数据库的行数?

发布于 2025-01-03 12:45:57 字数 920 浏览 0 评论 0原文

我有下表,

+-----------+------------------+------+-----+---------+----------------+
| 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 DELETEs 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅气尐潴 2025-01-10 12:45:57

按照这些思路应该可以工作:

DELETE FROM
  table 
WHERE
 userID = xyz and id not in (
  SELECT id FROM table WHERE userID = xyz ORDER BY logintime DESC LIMIT 10
 )

-- 补充:其中 userID = xyz

Something along these lines should work:

DELETE FROM
  table 
WHERE
 userID = xyz and id not in (
  SELECT id FROM table WHERE userID = xyz ORDER BY logintime DESC LIMIT 10
 )

-- added: where userID = xyz

凹づ凸ル 2025-01-10 12:45:57
DELETE from table
WHERE id NOT IN(
      SELECT id FROM table GROUP BY userid ORDER BY logintime DESC LIMIT 10)
DELETE from table
WHERE id NOT IN(
      SELECT id FROM table GROUP BY userid ORDER BY logintime DESC LIMIT 10)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文