Is too many Left Joins a code smell?

前端 未结 8 1729
南笙
南笙 2021-01-01 09:30

If you have for example > 5 left joins in a query is that a code smell that there is ...

  • something wrong with your design?
  • you\'re doing too much in o
相关标签:
8条回答
  • 2021-01-01 09:51

    It's a perfectly legitimate solution for some designs.

    Say you have a hierarchy of one-to-many relations like Customer - Order - Basket - Item - Price, etc., which can be unfilled on any level: a Customer may have no Orders, an Order can have no Baskets, etc.

    In this case you issue something like:

    SELECT  *
    FROM    Customer c
    LEFT OUTER JOIN
            Order o
    ON      o.CustomerID = c.ID
    LEFT OUTER JOIN
            Basket b
    ON      b.OrderID = c.ID
    …
    

    Note that it may be inefficient in some cases, and may be replaced with EXISTS or NOT EXISTS (if you only want to figure out that the corresponding records exist or do not exist in other tables).

    See this article in my blog for performance details:

    • Finding incomplete orders - how to benefit from replacing LEFT JOIN's with NOT EXISTS
    0 讨论(0)
  • 2021-01-01 09:51

    Your Results My Vary

    Anything out of the ordinary could be a code-smell for anything. Like Quassnoi said it could be perfectly legitimate. It's not uncommon for really in-depth reports to require a crazy amount of joins to piece together the information correctly. That doesn't mean that the developer should looking at denormalizing their database.

    0 讨论(0)
提交回复
热议问题