exists& distinct

    技术2022-05-19  24

    exists :用于检查子查询返回的行的存在性, distinct用于禁止重复行的显示.  因为distinct 在禁止重复行之前要排序检索到的行, 很多书上建议私用exists 代替 distinct, 如下面的例子:

     

    -- BAD uses DISTINCT

    -- 检索已经购买的产品

    -- products 产品表  :product id 唯一

    -- purchases 购物表 : product id  foreign key

    select distinct pr.product_id, pr.name

    from products pr, purchases pu

    where pr.product_id = pu.product_id

     

     

    -- 用exists 替代

    select product_id, name

    from products outer

    where exists(

     select 1

     from purchases inner

     where inner.product_id = outer.product_id);

     

     

    --上面这个例子之所以能对重复行的排除, 是因为在products 表里每一个product id 本来就是唯一的,

    选出来后,当然不会重复, 不要生搬硬套的认为 所有的distinct 都可以用 exists 替换.

     

    如:当我们只知道purchases 表时(不知道products 表), 要看purchases 表中的product_id (排重复)

    这个时候就只能用distinct 了,

     

    select distinct product_id

    from  purchases

     

     

     

     


    最新回复(0)