繁体   English   中英

如何从一个表中选择ID,该ID存在于两个表之一中,但不存在于其他两个表中的一个中

[英]How can I select from one table where the ID exists in one of two tables, but not in either of other two tables

这听起来令人困惑,但是想法很简单。

我想获取具有默认费率的产品列表,但是给定的“代理商”没有费率。 为此,我需要从下表中进行选择

    t_Products
|-ProductID-|--Product-|
|   100     | Product1 |
|   101     | Product2 |
|   102     | product3 |
|   103     | product4 |

ID在t_Annual_DefaultCost或t_Daily_DefaultCost中存在的位置

    t_Annual_DefaultCost
|-DefaultID-|-ProductID-|--Cost-|
|    100    |     100   | 24.00 |
|    101    |     101   | 26.00 |

    t_Daily_DefaultCost
|-DefaultID-|-ProductID-|--Cost-|-Days-|
|    100    |     100   | 24.00 |   1  |
|    101    |     100   | 26.00 |   2  |
|    102    |     102   | 22.50 |   2  |
|    103    |     102   | 97.50 |   8  |

但是对于给定的代理ID,它不能存在于t_Annual_AgentCost或t_Daily_AgentCost中

    t_Annual_AgentCost 
|---CostID--|-ProductID-|-AgentID-|--Cost-|
|    100    |    100    |  10001  | 24.00 |
|    101    |    100    |  10001  | 20.00 |

    t_Daily_AgentCost
|---CostID--|-ProductID-|-AgentID-|--Cost-|-Days-|
|    100    |     100   |  10001  | 24.00 |   1  |
|    102    |     102   |  10002  | 35.00 |   2  |

因此对于AgentID 10001,最终结果应为

|-ProductID-|--Product-|
|   101     | product2 |
|   102     | product3 |

对于AgentID 10002,最终结果应为

|-ProductID-|--Product-|
|   100     | product1 |
|   101     | product2 |

我目前正在使用以下代码来获取具有默认费率的产品列表。 但是我不知道如何在AgentCost表中也删除/不获取那些。

Select 
    distinct a.* 
from 
    t_Products as a
inner join
    ( 
        select 
            DefaultID ,ProductID
        from 
            t_Daily_DefalutCost 

        union 

        select 
            DefaultID , ProductID
        from 
            t_Annual_DefaultCost 
    ) 
    as b on a.ProductID = b.ProductID

如果您想一次做一名特工,那么这就是我的做法:

SELECT
    a.* 
FROM
    t_Products As a
WHERE
    (   EXISTS( SELECT * FROM t_Daily_DefaultCost  As d WHERE d.ProductID = a.ProductID )
     OR EXISTS( SELECT * FROM t_Annual_DefaultCost As d WHERE d.ProductID = a.ProductID )
     )
AND NOT
    (   EXISTS( SELECT * FROM t_Daily_AgentCost    As d 
                WHERE d.ProductID = a.ProductID
                AND   d.AgentID   = @SpecifedAgentID )
     OR EXISTS( SELECT * FROM t_Annual_AgentCost   As d 
                WHERE d.ProductID = a.ProductID
                AND   d.AgentID   = @SpecifedAgentID )
     )

这里的OR EXISTSUNION ALL SELECT几乎一样。

我会使用这种方法。

select yourfields
from yourtables
where id in 
(

(select id
 from onetable
 union
 select id
 from anothertable)
 except
 (select id
  from yetanothertable
  union
  select id
  from thefinaltable)
)

您可以填写实际的表名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM