开发者

Joining on 1 column across 4 tables - Mysql

I'm going over some SQL I wrote a while ago that joins 4 tables on a common ID column. I'm getting a little paranoid about my join, and I hope someone can just clear this simple concept up for me:

SELECT A.adata, B.bdata, C.cdata, D.ddata 
FROM taba A, tabb B, tabc C, tabd D
WHERE A.id=B.id AND B.id=C.id AND C.id=D.id
AND A.id=C.id AND A.id=D.id AND B.id=D.id

Do I need all those AND clauses, or can I eliminate the last 3, like this:

SELECT A.adata, B.bdata, C.cdata, D.ddata 
FROM taba A, tabb B, tabc C, tabd D
WHERE A.id=B.id AND B.id=C.id AND C.id=D.id

Although I've successfully tested the smaller query on my dataset and it appears to yield the same result, I don't want to have some incomplete SQL come back to haunt me. On the other hand, I don't want to load up on unnecessary conditions. Let me know if I can provide additional information.

-- UPDATE, thanks for answers everyone. About the tables: they are relatively static although some values within the rows change throughout the day. Each table A, B, C, D st开发者_Python百科ores different information about OBJECT, and the OBJECT ID is common across all 4, so it's very straightforward here.


A better solution to make it far easier to read is to use the ISO/ANSI Join syntax:

Select A.adata, B.bdata, C.cdata, D.ddata 
From taba As A
    Inner Join tabb As B
        On B.id = A.id
    Inner Join tabc As C
        On C.id = B.id
    Inner Join tabd As D
        On D.id = C.Id


Your second version takes advantage of the transitive relationship between the table columns.

A simpler way to think about it would be.

A = 1, B = A, therefore B = 1


I agree you should use the INNER JOIN syntax, to make it easier to follow.

But you should also keep in mind that those AND clauses may be used by the optimizer. Without knowing how your tables are built I can't say for sure. But in general, if you tell the database to join based on two columns, it will attempt to use indexes, if they exist. If you replace those using the "transitive property", then you might make the query run slower.

Just a warning. It depends on your specific table structure.

If you tested it and it runs just as fast, it may be fine. But are the tables growing? Might it fail over time? I would be concerned about that, and test it with very large tables before making the change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜