Query performance: Query on multiple tables Vs. Composite query

笑着哭i 提交于 2019-12-31 07:04:02

问题


Table A has column srno and few other columns.

Table B has columns srno and id.

I want to get srno from B for given id and then fetch out record(s) for that srno from table A.

For example, if id is 7 then I can think of doing this by two ways:

select * from A as table_a, B as table_b where table_a.srno=table_b.srno and table_b.id=7;

And,

select * from A where srno in (select srno from B where id=7);

Both are doing same. But when there are huge number of records in both the tables, performance wise which is better? Or both would have same performance? (Let's assume here that proper indexing etc has been taken care on these two tables. I just want performance comparison between these two queries)


回答1:


Your second query will always be slower. That type of dynamic IN clause in MySQL is never a good approach.

My recommendation would be to use the first query, but rewrite it using ANSI joins syntax and select the minimal set of columns you need, rather than doing SELECT *.

This would be a good starting point:

select table_a.* 
from A as table_a 
inner join B as table_b on table_a.srno=table_b.srno 
where table_b.id=7;


来源:https://stackoverflow.com/questions/31389563/query-performance-query-on-multiple-tables-vs-composite-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!