简体   繁体   中英

Is there an alternative to joining 3 or more tables?

Is it a good idea to join three or more tables together as in the following example. I'm trying to focus on performance. Is there any way to re-write this query that would be more efficient and faster performing? I've tried to make is as simplistic as possible.

select * from a
join b on a.id = b.id 
join c on a.id = c.id
join d on c.id = d.id
where a.property1 = 50 
    and b.property2 = 4 
    and c.property3 = 9 
    and d.property4 = 'square'

If you want faster performance, make sure that all of the join's are covered by an index (either clustered or non-clustered). It looks like this could all be done in your query above by creating an index on the id and appropriate property columns of each table

如果您只选择列的一个子集,则可以更快地进行操作,此刻您正在从所有3个表中选择所有内容。

Assuming a normalized database, this is the best you can do, in terms of structuring a query and the joins in place.

There are other options to look at, including adding indexes on the different join and select clause columns, denormalizing the table structures and narrowing the result set.

Adding indexes on the join columns (which appear to be primary keys, so may already be indexed) will help with the join performance, indexing the columns in the select clause will help with speeding up the filtering on each table.

If you denormalize, you get a structure with duplicate data with all the implications of duplicate data (data maintenance issues mostly), but you gain performance as you no longer need to join.

When selecting columns, you should specify which ones you want - using * is generally a bad idea. This way you only transfer the data that the application really needs.

Performance wise, I think it really depends on the number of records in each table, and making sure that you have the proper indexes defined. (I'm also assuming that SELECT * is a placeholder; you should avoid wildcards)

I'd start off by checking out your execution plan, and start optimizing there. If you're still getting suboptimal performance, you could try using temp tables to break up the 4 table join into separate smaller joins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM