使用联接获取记录

时间:2019-04-17 16:20:55

标签: sql oracle join

下面是示例数据和返回结果的查询。

create table tab1 (grp_id number, mid number);
create table tab2 (grp_id number, mid number);

insert into tab1 values(1, 5);
insert into tab1 values(1, 6);
insert into tab1 values(1, 7);
insert into tab1 values(1, 8);
insert into tab1 values(2, 9);
insert into tab1 values(2, 10);

insert into tab2 values(1, 5);
insert into tab2 values(1, 6);
-----------------------------------------
select *
  from tab1 t1, tab2 t2
 where t1.mid = t2.mid(+)
   and t1.grp_id in (select grp_id from tab2)
  ;
| GRP_ID | MID | GRP_ID |    MID |
|--------|-----|--------|--------|
|      1 |   5 |      1 |      5 |
|      1 |   6 |      1 |      6 |
|      1 |   7 | (null) | (null) |
|      1 |   8 | (null) | (null) |

我是否可以不使用In或Exists子句而获得上述结果。请确保这是示例数据

请帮助谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用相关查询,其中外部查询中的列作为内部查询的参数进入。 这是唯一的解决方案:

# Get list of files
files = glob.glob(os.path.join(" ", "/home/cloudera/Desktop/sample/*"))
# Read list of files into a list of dataframes
df_list = [pd.read_csv(f, header = None) for f in files]
# Stack all dataframes into one (you can change the parameters as you want)
df = pd.concat(df_list, ignore_index = True, sort = False) 

检查http://sqlfiddle.com/#!4/f9113e/2

谢谢!!!!

答案 1 :(得分:1)

是的,您可以直接使用left join来获得结果

select t1.grp_id as grp_id_1,t1.mid as mid_1,
       t2.grp_id as grp_id_2,t2.mid as mid_2
  from tab1 t1 
  left join tab2 t2 on t1.grp_id=t2.grp_id and t1.mid=t2.mid
 where t1.grp_id=1;

Demo