如何实现这个oraclesql?

ztmd8pv5  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(298)

我有两个虚拟表,其中插入了这些定义和数据: create table stock_collection(id_collection number primary key , name varchar(10)); ```
create table mycollection(id_collection primary key ,
name varchar(10) ,
CONSTRAINT fk_supplier
FOREIGN KEY (id_collection)
REFERENCES stock_collection(id_collection));

insert into stock_collection values(1,'col1');
insert into stock_collection values(2,'col2');
insert into stock_collection values(3,'col3');
insert into stock_collection values(4,'col4');

insert into mycollection values(1,'col1');
insert into mycollection values(2,'col2');

我的目标是返回一个包含表中所有数据的查询 `stock_collection` 有一个额外的列告诉你 `id_collection` 表的 `stock_collection` 表中是否存在 `mycollection` .
结果应该是这样的:

id_collection Name exists_in_my_collection
1 col1 true
2 col2 true
3 col3 false
4 col4 false

rn0zuynd

rn0zuynd1#

使用 exists :

select sc.id_collection, sc.Name,
       (case when exists (select 1
                          from mycollection mc
                          where sc.id_collection = mc.i  d_collection
                         )
             then 'TRUE' else 'FALSE'
        end)
from stock_collection sc;

我强烈建议 case 结束 left join 因为它保证没有重复的行。数据模型中的任何内容都不排除重复,而且您的问题基本上意味着您不希望复制数据模型中的行 stock_collection .
oracle也有可能会对此进行更好的优化,但如果考虑到这一点,则需要对大量数据进行测试。

zbdgwd5y

zbdgwd5y2#

做一个 LEFT JOIN ,如果mycollection.id\u collection列不为null,则mycollection表中存在一行,否则不存在。

select sc.id_collection, sc.Name,
       case when mc.id_collection is not null then 'TRUE' else 'FALSE' end
from stock_collection sc
left join mycollection mc
  on sc.id_collection = mc.id_collection
w1jd8yoj

w1jd8yoj3#

SQL> select sc.id_collection, sc.name,
  2  case when mc.id_collection is not null then 'true' else 'false' end as exists_in_my_collection
  3  from stock_collection sc
  4  left join mycollection mc
  5  on sc.id_collection = mc.id_collection;

ID_COLLECTION NAME   EXIST
------------- ---------- -----
        1 col1   true
        2 col2   true
        3 col3   false
        4 col4   false

SQL>
pgvzfuti

pgvzfuti4#

使用 exists :

select sc.id_collection, sc.Name,
       (case when exists (select 1
                          from mycollection mc
                          where sc.id_collection = mc.i  d_collection
                         )
             then 'TRUE' else 'FALSE'
        end)
from stock_collection sc;

相关问题