首页 > 解决方案 > Oracle SQL - 加入和拥有

问题描述

我试图获取在合同表中出现多次的帐户,无论它在 c_map 表中加入的次数如何。

CREATE TABLE cntrct (
  cntrct_id VARCHAR(10),
  account_id varchar(10)
);
CREATE TABLE c_map (
  cntrct_id VARCHAR(10)
);


INSERT INTO cntrct VALUES (1,'a');
insert into cntrct values (2,'b');
insert into cntrct values (3,'c');
insert into cntrct values (4,'b');

INSERT INTO c_map VALUES (1);
INSERT INTO c_map VALUES (1);
INSERT INTO c_map VALUES (1);
insert into c_map values (2);
insert into c_map values (2);
insert into c_map values (2);
insert into c_map values (3);
insert into c_map values (3);
insert into c_map values (3);
commit;

select ct.account_id
from cntrct ct, c_map cm
where ct.cntrct_id = cm.cntrct_id
group by ct.account_id
having count(ct.account_id)> 1

小提琴: http ://sqlfiddle.com/#!4/cec1b7/4

我期待输出:

 b

但相反,我得到了所有这些。如何限制它,以便在运行 count()>1 时不考虑 c_map 表?

谢谢,

标签: sql

解决方案


获取在合同表中出现多次的帐户,无论它在 c_map 表中加入的次数。

为什么要加入?您想要的信息在合同表中:

select account_id
from cntrct 
group by account_id
having count(*) > 1

也许您想根据映射表中存在的合同 ID 过滤数据集。如果是这样,我会推荐 exists

select account_id
from cntrct c
where exists (select 1 from c_map m where m.cntrct_id = c.cntrct_id)
group by account_id
having count(*) > 1

推荐阅读