Mysqli在同一个表中循环遍历每个ID超过3条记录

时间:2015-09-12 10:15:03

标签: php mysql mysqli

这是我的表:

placeID | name | time

如果placeID在表格中有超过3条记录,我的目标是删除最早的记录。

这很难理解,所以这个例子会说清楚:

1 | "Some Name" | *fresher timestamp*
1 | "Some Name" | *fresher timestamp*
1 | "Some Name" | *older timestamp* -- > Delete this result since there are more than 3 records, and this is the older than the rest
1 | "Some Name" | *older timestamp* -- > Delete this result since there are more than 3 records, and this is older than the rest
1 | "Some Name" | *fresher timestamp*
2 | "Some Name" | *fresher timestamp*
2 | "Some Name" | *fresher timestamp*

我的麻烦:如何为表格中包含3条以上记录的每个placeID循环?

删除最旧的结果不会有问题。

我尝试了什么:

SELECT placeID,COUNT(placeID) FROM place_fbStatus WHERE count(placeID) > 3

错误:#1111 - 无效使用群组功能

另一个尝试:

SELECT id, placeID
FROM place_fbStatus
HAVING COUNT( placeID ) >4
LIMIT 0 , 30

问题:只显示一个placeID

3 个答案:

答案 0 :(得分:2)

我的答案:

首先要在你的桌子上创建一个PRIMARY KEY。所以很容易用这个删除行。

创建表格

CREATE TABLE `mytable` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `placeID` INT(11) DEFAULT NULL,
  `name` VARCHAR(32) DEFAULT NULL,
  `time` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `placeID` (`placeID`,`time`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

插入一些内容:

INSERT INTO `mytable` (`id`, `placeID`, `name`, `time`)
VALUES
    (1, 1, 'Some Name', '2015-01-01 00:00:00'),
    (2, 1, 'Some Name', '2015-01-02 00:00:00'),
    (3, 1, 'Some Name', '2015-01-10 00:00:00'),
    (4, 1, 'Some Name', '2015-01-09 00:00:00'),
    (5, 2, 'Some Name', '2015-02-01 00:00:00'),
    (6, 2, 'Some Name', '2015-01-30 00:00:00'),
    (7, 1, 'Some Name', '2015-01-08 00:00:00');

我添加了rid(每个地方的ROW ID),行的顺序正确

SELECT @rid:=IF( @pid = m.placeID, @rid+1 , 1) rid, m.*, @pid:=m.placeID AS pid
      FROM mytable m, (SELECT @rid:=0, @pid:=-1) AS tmp 
      ORDER BY placeID,TIME ASC

最后查询要删除行:

DELETE mt FROM mytable mt
INNER JOIN (
  SELECT * FROM (
    SELECT @rid:=IF( @pid = m.placeID, @rid+1 , 1) rid, m.*, @pid:=m.placeID AS pid
      FROM mytable m, (SELECT @rid:=0, @pid:=-1) AS tmp 
      ORDER BY placeID,TIME ASC
  ) AS x
  WHERE x.rid >3
) AS dt ON mt.id = dt.id ;

答案 1 :(得分:0)

你几乎钉了它。你需要的是组合GROUP BY和HAVING

SELECT placeID, count(placeID) AS cnt
  FROM place_fbStatus 
  GROUP BY placeID HAVING cnt>3

答案 2 :(得分:0)

DELETE FROM Table WHERE ID NOT IN (SELECT TOP 3 ID FROM Table)

请参阅this thread

虽然看起来在自己尝试之后,似乎某些版本的mysql还没有支持子查询中的限制子句(这个版本的MySQL还没有支持' LIMIT& IN / ALL / ANY /一些子查询')。要解决此问题,请尝试使用不涉及限制的备用子查询。