The meaning of life is to explore the world

SQL table joining special skill

Posted on By Jason Liu

An example of SQL table joining special skill

Problem:

my_image

After the BigTable joins SmallTable, the smallCol cannot exceeds n
Now we want all records including unmatched_K in BigTable have smallCol
But we are not allowed to change these two tables or change the joining logic on matched_K
It seems impossible right?
It is possible!

Solution:

my_image

If BigTable joins MIdTable then joins SmallTable, then it can be done (where 1<=x<=y<=n in MidTable) Use the SQL below:

select b.A, coalesce(sb.B, sm.B)
from BigTable b left join MidTable m on b.A=m.A
    left join SmallTable sb on b.A=sb.A
    left join SmallTable sm on m.B=sm.A