【问题标题】:sql : join table ,return record with count 1sql:连接表,返回计数为1的记录
【发布时间】:2021-03-30 21:30:57
【问题描述】:

我有一张桌子mt table 它存储交易。 每笔交易都有一个帐单,并由 external_id 字段加入

我想从账单表只有一条连接记录的 mt 表中返回数据。

所以在这种情况下我会返回(mttable,id:4 和 2。它的 external_id 111 和 222 在计费表中只有一条记录)

mt table
id        external_id
---       -----------
1          444
2          222
3          333
4          111

billing table

id      external_id
---     -----------
3        444
4        444
5        333
6        333
7        222
8        111

【问题讨论】:

    标签: sql oracle11g oracle-sqldeveloper


    【解决方案1】:

    您可以在这里使用基本的GROUP BY 查询:

    SELECT mt.id, mt.external_id
    FROM mt
    INNER JOIN billing b ON b.external_id = mt.external_id
    GROUP BY mt.id, mt.external_id
    HAVING COUNT(*) = 1;
    

    Demo

    【讨论】:

      【解决方案2】:

      嗯。 . .

      select mt.*
      from mt
      where (select count(*)
             from billing b
             where mt.external_id = b.external_id
            ) = 1;
      

      【讨论】:

        【解决方案3】:

        您可以执行以下操作:

        SELECT * FROM mt WHERE external_id IN 
        (SELECT external_id FROM billing GROUP BY external_id HAVING COUNT(*) = 1)
        

        【讨论】:

          【解决方案4】:

          还有一些其他的选择,比如NOT EXISTS:

          select t.*
            from mt t join billing b on t.external_id = b.external_id 
           where not exists 
              (select 1 from billing bb
                 where mt.external_id = b.external_id and b.id <> bb.id);
          

          或者你也可以使用解析函数count,如下:

          select * from
          (select t.*, count(1) over (partition by b.external_id) as cnt
            from mt t join billing b on t.external_id = b.external_id)
          where cnt = 1
          

          【讨论】:

            猜你喜欢
            • 2023-03-12
            • 1970-01-01
            • 2019-07-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多