简体   繁体   English

表之间的多个联接

[英]Multiple joins between tables

I have following tables have multiple records each (~50k) and the tables are growing. 我有以下表,每个表都有多个记录(〜50k),并且表正在增长。

Table1
BatchID ID Record1

Table 2 
BatchID ID Record2

Table 3
BatchID ID Record3

Table 4 
BatchID ID Record4

The following query takes forever to run (as the join is the cartisian product of the four tables). 以下查询将永远运行(因为联接是四个表的笛卡尔积)。

Select table1.batchid,
table1.ID,
table1.Record1, 
table2.Record2,
Table3.Record3, 
Table4.Record4 
from Table1 JOIN Table 2
on table1.batchID = table2.batchID and table1.ID = table2.ID
JOIN table3 
on table1.BatchID=table3.batchID and table1.ID = table3.ID 
JOIN table4 
on table1.ID = table4.ID and table1.batchID = table4.batchID 

What should be the best way to do this. 什么应该是最好的方法做到这一点。

You should add indexes with both columns you are using in the ON clauses. 您应该在ON子句中同时使用两列添加索引。 For example: 例如:

ALTER TABLE `table2` ADD INDEX `IDX_batchid-ID` (`batchid`, `ID`);

The first thought is that you want a composite index on (batchid, id) on all four tables. 首先想到的是,您希望对所有四个表都使用(batchid,id)的复合索引。 This will best match the join condition in the query. 这将最匹配查询中的连接条件。

How many records in the tables match each other with the same batchid and id? 表中有多少条记录具有相同的batchid和id相互匹配? There may be other ways to phrase the query. 可能还有其他方式来短语查询。

Your join looks fine. 您的加入看起来不错。 Try creating an index on the combination of BatchID and ID. 尝试在BatchID和ID的组合上创建索引。

dev.mysql.com dev.mysql.com

Do you actually need all these JOINs? 您实际上是否需要所有这些JOIN? Can't you just merge these four tables together? 您不能将这四个表合并在一起吗?

For example: 例如:

CREATE TABLE MergedTable (
    BatchID INT,
    ID INT,
    Record1 ... ,
    Record2 ... ,
    Record3 ... ,
    Record4 ... ,
    PRIMARY KEY (BatchID, ID)
)

And then: 接着:

INSERT INTO MergedTable <your query>

You can now SELECT directly from MergedTable, without need for any JOINs. 现在,您可以直接从MergedTable中进行SELECT,而无需任何JOIN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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