Join vs. sub-query

前端 未结 19 2013
广开言路
广开言路 2020-11-21 05:05

I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don\'t know why.

19条回答
  •  迷失自我
    2020-11-21 05:23

    Subqueries have ability to calculate aggregation functions on a fly. E.g. Find minimal price of the book and get all books which are sold with this price. 1) Using Subqueries:

    SELECT titles, price
    FROM Books, Orders
    WHERE price = 
    (SELECT MIN(price)
     FROM Orders) AND (Books.ID=Orders.ID);
    

    2) using JOINs

    SELECT MIN(price)
         FROM Orders;
    -----------------
    2.99
    
    SELECT titles, price
    FROM Books b
    INNER JOIN  Orders o
    ON b.ID = o.ID
    WHERE o.price = 2.99;
    

提交回复
热议问题