sql : 加入 table ,return 记录,计数为 1

sql : join table ,return record with count 1

我有一个tablemt table 它存储交易。 每笔交易都有一个账单,并由 external_id 字段加入

我想 return 来自 mt table 的数据,其中账单 table 只有一个加入的记录。

所以在这种情况下我会 return (mttable, id:4 and 2. external_id 111 and 222 has only one record in billing table)

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

嗯。 . .

select mt.*
from mt
where (select count(*)
       from billing b
       where mt.external_id = b.external_id
      ) = 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

您可以执行以下操作:

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

还有一些其他选项,例如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