我的查询示例是:
select * from table1
where table1_seq = (select table2_seq from table2 where ~)
然后子查询操作table1的Data ??
的每一行或
只运行一次?
IF一次,那么上层查询或使用连接查询之间哪个性能更好?
答案 0 :(得分:0)
使用您的查询,只有在子查询返回1并且只有1个结果时才会返回错误。
你应该对查询做一个解释:
Explain select * from table1
where table1_seq = (select table2_seq from table2 where id2=X)
将返回类似的内容:
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra
==========================================================================================================================================================
1 | PRIMARY | Table1 | NULL | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | NULL
2 | SUBQUERY | Table2 | NULL | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | Using index
内部加入另一方面也会做2个查询:
EXPLAIN select table1.*
from table1
INNER JOIN table2 ON table1.table1_seq = table2.table2_seq
WHERE table2.id2=X
结果:
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra
==========================================================================================================================================================
1 | SIMPLE | Table1 | NULL | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | NULL
2 | SIMPLE | Table2 | NULL | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | NULL
所以它不是基准问题,而是更多关于你想做什么的问题。如果您只想从另一个表中选择1个值,您可以真正执行您编写的查询。