mysql Is there a way to have 1 to many relationship join in Big Query? I want to repeat values using full outer join but it returns inner join

sd2nnvve  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(124)

I have a table with a ranking keywords and join another table where the keyword exists but when I apply an outer join, it only returns the inner join since there are multiple matches to 1.
What I have:

What I want:

I tried several different joins but it doesn't return what I want. It always returns an inner join.

swvgeqrz

swvgeqrz1#

You can achieve your desired output by joining each table separately and then applying union on those results.You can try the below query :

Query:

create temp table main as (
 select 1 ranking, 'apple' keyword, 500 total_purchase union all
 select 2,'banana', 477  union all
 select 3, 'milk', 456
);
 
create temp table t1 as (
 select 1 ranking, 'apple' keyword, 55 purchase, 1 store union all
 select 2,'beer', 42 ,1  union all
 select 3, 'chips', 33 ,1
);
 
create temp table t2 as (
 select 1 ranking, 'apple' keyword, 51 purchase, 2 store union all
 select 2,'banana', 43 ,2  union all
 select 3, 'bread', 34 ,2
);
 
select m.*,t.purchase,first_value(Store ignore nulls) over
( order by m.ranking) store from main m
left join t1 t on m.keyword = t.keyword
union all
select m.*,t.purchase,first_value(Store ignore nulls) over( order by 
m.ranking) store from main m
left join t2 t on m.keyword = t.keyword

Output:

相关问题