如何转换' not in'声明加入group by

时间:2014-11-05 10:24:47

标签: mysql sql join group-by

如何获取所有记录,除了最新的记录按记录分组?

表:

attachments
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| record_id | int(11)          | NO   |     | NULL    |                |
| created   | date             | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+

表附件中的源测试行:

mysql> select * from attachments;
+----+-----------+------------+
| id | record_id | created    |
+----+-----------+------------+
|  1 |         1 | 2014-11-05 |
|  2 |         1 | 2014-11-04 |
|  3 |         1 | 2014-11-03 |
|  4 |         1 | 2014-11-02 |
|  5 |         2 | 2014-11-05 |
|  6 |         2 | 2014-11-04 |
|  7 |         2 | 2014-11-03 |
+----+-----------+------------+

我创建了这个查询,但是对于大表来说它太慢了:

SELECT * FROM attachments WHERE id NOT IN (
SELECT 
attachments.id
FROM attachments
GROUP BY attachments.record_id
ORDER BY attachments.`created` DESC
)

结果:

+----+-----------+------------+
| id | record_id | created    |
+----+-----------+------------+
|  2 |         1 | 2014-11-04 |
|  3 |         1 | 2014-11-03 |
|  4 |         1 | 2014-11-02 |
|  6 |         2 | 2014-11-04 |
|  7 |         2 | 2014-11-03 |
+----+-----------+------------+

我的联接查询得到其他方式的结果,选择仅由record_id分组的最新内容:

SELECT  old.*
FROM attachments `old`
INNER JOIN attachments `new` ON `new`.id = `old`.id
GROUP BY new.record_id
ORDER BY old.`created` DESC

结果:

+----+-----------+------------+
| id | record_id | created    |
+----+-----------+------------+
|  1 |         1 | 2014-11-05 |
|  5 |         2 | 2014-11-05 |
+----+-----------+------------+

将INNER更改为RIGHT或LEFT不会更改输出结果。

2 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT t1.* FROM attachments t1 
left outer join
(SELECT attachments.id
FROM attachments
GROUP BY attachments.record_id
ORDER BY attachments.`created` DESC) t2 on t1.id = t2.id
where t2.id is null;

SQL Fiddle

答案 1 :(得分:0)

Select *
From attachments a
Where exists (Select *
              From attachments a2
              Where a.record_id = a2.record_id
              and   a.created < a2.created);

此查询检查以确保存在具有相同记录ID的其他数据和更新的创建日期。如果您有两个具有相同record_id的ID并且创建日期为两个最新记录,则此操作无效。此查询将忽略它们。