我有两张桌子:
表groupMessage
用于记录组用户消息
表groupMessageNum
用于记录消息数超过300的记录。
-------------------
| groupMessage |
|-----------------|
| id |
| hostId |
| roomId |
===================
---------------------
| groupMessageNum |
|-------------------|
| id |
| hostId |
| roomId |
=====================
我正在尝试删除groupMessage
中groupMessageNum
中的记录,并删除groupMessageNum
中的记录。
如果要删除的groupMessage
中的记录数超过300,我将删除第300条记录后的记录。
我的sql是:
delete group, groupNum from groupMessage group, groupMessageNum
groupNum where group.hostId = groupNum.hostId and group.roomId =
groupNum.roomId;
这将删除groupMessage中的所有记录。
那么,我怎样才能删除300日后的记录?
示例:
有100个用户,60个用户有超过300条消息。所有用户消息都在groupMessage表中。 60个用户ID在groupMessageNum中,因为他们的消息超过300个。
现在我正在尝试删除第300条消息之后的用户消息。所以我首先在groupMessageNum表中找到userid,然后在groupMessage表中删除这些消息。
答案 0 :(得分:2)
您可以尝试这样的事情:
DELETE group, groupNum
FROM groupMessage group
INNER JOIN (SELECT hostId
FROM group
ORDER BY msgTime ASC
LIMIT 300, 9999999999
) group2
ON group.hostId = group2.hostId
INNER JOIN groupMessageNum groupNum
ON group.hostId = groupNum.hostId AND
group.roomId = groupNum.roomId;
或其他方式你可以试试这个:
DELETE group, groupNum
FROM groupMessage group
INNER JOIN (SELECT hostId, (@rank := @rank + 1) AS rank
FROM group, (SELECT @rank:= 0) a
ORDER BY msgTime ASC
) group2
ON group.hostId = group2.hostId AND
rank > 300
INNER JOIN groupMessageNum groupNum
ON group.hostId = groupNum.hostId AND
group.roomId = groupNum.roomId;
答案 1 :(得分:0)
DELETE A, B
FROM groupMessage A
INNER JOIN groupMessageNum B on A.hostId = B.hostId and A.roomId=B.roomId
INNER JOIN (SELECT id FROM groupMessage LIMIT 300,999999) C
ON A.id = B.id