我有两个表table1,table2它们的定义是:
table1
table2
CREATE `table1` ( 'table1_id' int(11) NOT NULL AUTO_INCREMENT, 'table1_name' VARCHAR(256), PRIMARY KEY ('table1_id') ) CREATE `table2` ( 'table2_id' int(11) NOT NULL AUTO_INCREMENT, 'table1_id' int(11) NOT NULL, 'table1_name' VARCHAR(256), PRIMARY KEY ('table2_id'), FOREIGN KEY ('table1_id') REFERENCES 'table1' ('table1_id') )
我想知道未在table1中引用的行数table2,可以通过以下方式完成:
SELECT COUNT(t1.table1_id) FROM table1 t1 WHERE t1.table1_id NOT IN (SELECT t2.table1_id FROM table2 t2)
有没有更有效的方法来执行此查询?
升级到MySQL 5.6,可以更好地针对子查询优化半联接。
见http://dev.mysql.com/doc/refman/5.6/en/subquery- optimization.html
否则使用排除联接:
SELECT COUNT(t1.table1_id) FROM table1 t1 LEFT OUTER JOIN table2 t2 USING (table1_id) WHERE t2.table1_id IS NULL
另外,请确保上面table2.table1_id有一个索引。
table2.table1_id