代码之家  ›  专栏  ›  技术社区  ›  Dennis

如何构造一个sql来创建一个报表,该报表选择带有一个certian行项目的所有引号,如果在该引号上,则包括另一个项目?

  •  0
  • Dennis  · 技术社区  · 7 年前

    我有两张桌子:报价单和商品。

    报价表

    id | quote_number
    ---+-------
     1 |   100 
     2 |   200 
    

    项目表

    id | model | quote_id | other_data 
    ---+-------+----------+-----------
     1 |   ABC | 1        | xxx
     2 |  DISC | 1        | xxx
     3 |   ABC | 2        | xxx
     4 |  DISC | 2        | xxx
     3 |   XXX | 3        | xxx
     4 |  DISC | 3        | xxx
     3 |   ABC | 4        | xxx
    

    我需要创建一个报表,在其中选择必须包含模型的所有引号 ABC 如果是的话,我也想列出 DISC 属于那句话。我想列出所有这样的项目行。怎么用?

    用通俗易懂的英语说就是“给我所有的报价,上面有ABC范本 可以 也有与之相关的折扣(折扣)。

    示例报告

    quote_id | model | other_data 
    ---------+-------+---------+-
     1       |   ABC | xxx
     1       |  DISC | xxx
     2       |   ABC | xxx
     2       |  DISC | xxx
    

    到目前为止,我只能知道如何拉线。 基础知识 但我不知道该怎么做 圆盘 ,条件为“必须将ABC连接到同一报价”。

    4 回复  |  直到 7 年前
        1
  •  1
  •   Strawberry    7 年前

    可以使用子查询,如果使用MySQL 8,也可以使用CTE。

    SELECT it.quote_id, it.model, it.other_data
    FROM item it INNER JOIN (
        SELECT quote_id 
        FROM item i WHERE model = 'ABC') as sub_it 
    ON it.quote_id=sub_it.quote_id 
    WHERE it.model='ABC' OR it.model='DISC'
    ORDER BY it.quote_id DESC; 
    

    DB Fiddle

        2
  •  1
  •   Gordon Linoff    7 年前

    UNION ALL 似乎是个好办法:

    select ia.*
    from items ia
    where ia.model = 'ABC'
    union all
    select id.*
    from items id
    where id.model = 'DISC' and
          exists (select 1 from items ia where ia.quote_id = id.quote_id and ia.model = 'ABC')
    order by quote_id, model;
    

    这种逻辑可以利用索引 items(model) items(quote_id, model) . 这个 order by 任何解决方案都需要。

        3
  •  1
  •   Jim Castro    6 年前

    我认为子查询方法是最简单、最干净的方法。我不喜欢使用或条件,所以我改为使用in列表。

       SELECT
            quote_id,
            model,
            other_data
         FROM item 
        Where  quote_id in ( SELECT quote_id FROM item i WHERE model = 'ABC' )
          AND  model IN ('ABC', 'DISC')
        ORDER BY 1,2;
    
        4
  •  0
  •   DrEichenbach    7 年前

    您应该考虑join语句:

    SELECT quote_id, model, other_data FROM item i INNER JOIN quote q ON i.id = q.quote_id WHERE model = 'ABC' or model = 'DISC' ORDER BY quote_id DESC;