mysql - 如何将 'not in'语句转换为与group by连接

标签 mysql sql join group-by

如何获取除按 record_id 分组的最新记录之外的所有记录?

表:

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 不会更改输出结果。

最佳答案

尝试这个查询:

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

关于mysql - 如何将 'not in'语句转换为与group by连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754772/

相关文章:

mysql - 如何保存和保留日期毫秒(MySQL)

php - 使用 Ajax + JQuery + MySql + PHP 保存进度表单

php - 保护目录中 1000 多个 html 文件,无需全部编辑

sql - Postgres 是否会在更新时重写整行?

Gorm eager loading 加入多个关系

sql - SQL合并中发生无意的交叉连接

mysql - 两次使用复合键连接表

php - php 和 mysql 中的二叉树实现(家谱)

sql - 联合查询在一列上不同

sql - 如何在 SQL 代理作业中执行存储过程?