mysql - 替代子查询

标签 mysql sql subquery

给定下表:

CREATE TABLE IF NOT EXISTS `rank` ( 
`rank_id` bigint(20) NOT NULL AUTO_INCREMENT, 
`rank` int(10) NOT NULL DEFAULT '0', 
`subject_id` int(10) NOT NULL DEFAULT '0', 
`title_id` int(10) NOT NULL DEFAULT '0', 
`source_id` int(10) NOT NULL DEFAULT '0'
PRIMARY KEY (`rank_id`) 
) ENGINE=MyISAM; 

INSERT INTO `rank` (`rank_id`, `rank`, `subject_id`, `title_id`, `source_id`) VALUES 
(23, 0, 2, 1, 1), 
(22, 0, 1, 1, 1), 
(15, 0, 2, 2, 2), 
(14, 0, 2, 2, 1), 
(20, 0, 1, 3, 2), 
(18, 0, 1, 4, 2), 
(19, 0, 1, 5, 2), 
(21, 0, 1, 3, 1), 
(24, 0, 1, 6, 2); 

CREATE TABLE IF NOT EXISTS `title` ( 
`title_id` bigint(20) NOT NULL AUTO_INCREMENT, 
`title` varchar(255) DEFAULT NULL, 
`description` text, 
`pre` varchar(255) DEFAULT NULL, 
`last_modified_by` varchar(50) DEFAULT NULL, 
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
PRIMARY KEY (`title_id`) 
) ENGINE=MyISAM; 

INSERT INTO `title` (`title_id`, `title`, `last_modified`) VALUES 
(1, 'new item', ' ', '2011-10-20 19:10:48'), 
(2, 'another test', '2011-10-20 19:10:48'), 
(3, 'and yet another', '2011-10-20 19:10:48'), 
(4, 'one more', ' ', '2011-10-20 19:10:48'), 
(5, 'adding more', ' ', '2011-10-20 19:10:48'), 
(6, 'yes, another', ' ', '2011-10-20 19:10:48'), 
(7, 'well, let''s see', ' ', '2011-10-20 19:10:48'); 

我需要一个查询来选择与排名表中给定主题无关的所有标题。

我通过子查询来实现:

SELECT title_id, title FROM title
WHERE title_id NOT IN (SELECT title_id FROM rank WHERE subject_id=2)

这将返回所需的列表:

+----------+-----------------+ 
| title_id | title           | 
+----------+-----------------+ 
| 3        | and yet another | 
| 4        | one more        | 
| 5        | adding more     | 
| 6        | yes, another    | 
| 7        | well, let's see | 
+----------+-----------------+ 

但是,当查询大量数据时,它会变得有点慢。

我的问题是,是否有一种方法可以在不使用子查询的情况下返回此结果,以及这种替代方法是否更快。

提前致谢。

最佳答案

MySQL 的连接速度通常更快,尽管更快的子查询正在开发中。

SELECT t.*
FROM title AS t
LEFT JOIN rank AS r ON (t.title_id = r.title_id AND r.subject_id = 2)
WHERE r.title_id IS NULL

像往常一样,您需要在外键 (rank.title_id) 和查询键 (rank.subject_id) 上设置索引。

如果您需要更多详细信息,您应该阅读有关 [LEFT JOIN][1] 的 MySQL 文档。 ON 也有一个很好的技巧,使它不同于 WHERE

关于mysql - 替代子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844453/

相关文章:

Mysql "source"命令 : wrong exit code?

c# - 系统.Data.SqlTypes.SqlTypeException : SqlDateTime overflow

php - 如何将值插入联结表?

php - 用于获取每个级别的最后 3 行的 SQL

MySQL - 1toN,从 table1 中选择具有 table2.attribute=1 和 table2.attribute=2 的项目

php - 测试2个mysql数据库之间的内容

php - 为什么数据表默认不能按降序显示数据?

mysql - 模板工具包显示唯一行

php - Yii 关系子查询

mysql 使用 SUM 更新子查询