【问题标题】:how to get the part id by the order id and the part has no one else ordered如何通过订单 ID 获取零件 ID,并且该零件没有其他人订购
【发布时间】:2018-10-03 00:51:56
【问题描述】:

有表有 orer_id 和 part_id 字段。零件可以以多个顺序存在,例如 123、456 以 000000000001 和 000000000002 的顺序存在

| order_id     | part_id | 
=========================|
| 000000000001 | 00123   |  
| 000000000001 | 00456   | 
| 000000000001 | 00789   | 
| 000000000002 | 00123   | 
| 000000000002 | 00456   | 

想要找出由 order_id 订购的 part_id,但除了提供的 order_id 以外,其他人都没有订购该零件。

例如按oerder_id = 000000000001查询,想看结果{789}(因为123和456也是按其他order_id排序的)

【问题讨论】:

    标签: sql


    【解决方案1】:

    使用子查询

    select * from yourtable a
    where order_id = '1'
    and part_id not in (select part_id from yourtable where order_id <> a.order_id)
    

    【讨论】:

      【解决方案2】:

      您可以使用NOT EXISTS 和相关子查询,以检查具有相同部分的其他订单。

      SELECT t1.part_id
             FROM elbat t1
             WHERE t1.order_id = '000000000001'
                   AND NOT EXISTS (SELECT *
                                          FROM elbat t2
                                          WHERE t2.order_id <> t1.order_id
                                                AND t2.part_id = t1.part_id);
      

      【讨论】:

      • 应该AND NOT EXISTS (SELECT *AND NOT EXISTS (SELECT t2.order_id 吗?
      • @lannyf:这(几乎)从来没有什么不同。对于EXISTS,只有这样的记录是否存在才重要。 SELECT 之后的表达式(几乎)从未真正评估过(至少在几乎所有最近的 DBMS 中)。因此,如果您认为它看起来更好,您可以将其更改为您认为的任何内容。
      猜你喜欢
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2014-07-30
      • 2014-03-12
      • 2017-08-26
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      相关资源
      最近更新 更多