Which of the following SQL queries would be faster? A join on two tables or successive queries?

落爺英雄遲暮 提交于 2019-12-10 17:54:33

问题


I have two tables here:

ITEMS
ID| DETAILS| .....| OWNER

USERS:
ID| NAME|....

Where ITEMS.OWNER = USERS.ID

I'm listing the items out with their respective owners names. For this I could use a join on both tables or I could select all the ITEMS and loop through them making a sql query to retrieve the tuple of that itmes owner. Thats like:

1 sql with a JOIN versus 1x20 single table sql queries

Which would be a better apporach to take in terms of speed? Thanks


回答1:


Every query has overhead. If you can do something with one query, it's (almost) always better to do it with one query. And most database engines are smarter than you. Even if it's better to split a query in some way, the database will find out himself.

An example of overhead: if you perform 100 queries, there will be a lot more traffic between your application and your webserver.

In general, if you really want to know something about performance, benchmark the various approaches, measure the parameters you're interested in and make a decision based on the results of the becnhmark.

Good luck!




回答2:


Of course a JOIN will be faster.

Making 20 queries will imply:

  • Parsing them 20 times
  • Making 20 index seeks to find the start of the index range on items
  • Returning 20 recordsets (each with its own metadata).



回答3:


Executing a join will be much quicker as well as a better practice




回答4:


I join would be a lot quicker than performing another query on the child table for each record in the parent table.

You can also enable performance data in SQL to see the results for yourself..

http://wraithnath.blogspot.com/2011/01/getting-performance-data-from-sql.html

N



来源:https://stackoverflow.com/questions/4758712/which-of-the-following-sql-queries-would-be-faster-a-join-on-two-tables-or-succ

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