How do SQL EXISTS statements work?

前端 未结 7 501
不知归路
不知归路 2020-12-04 05:20

I\'m trying to learn SQL and am having a hard time understanding EXISTS statements. I came across this quote about \"exists\" and don\'t understand something:

7条回答
  •  死守一世寂寞
    2020-12-04 06:11

    EXISTS means that the subquery returns at least one row, that's really it. In that case, it's a correlated subquery because it checks the supplier_id of the outer table to the supplier_id of the inner table. This query says, in effect:

    SELECT all suppliers For each supplier ID, see if an order exists for this supplier If the supplier is not present in the orders table, remove the supplier from the results RETURN all suppliers who have corresponding rows in the orders table

    You could do the same thing in this case with an INNER JOIN.

    SELECT suppliers.* 
      FROM suppliers 
     INNER 
      JOIN orders 
        ON suppliers.supplier_id = orders.supplier_id;
    

    Ponies comment is correct. You'd need to do grouping with that join, or select distinct depending on the data you need.

提交回复
热议问题