sql - join one table if condition met otherwise from another table -
i want know sql query following condition
i have 3 tables, table 1 want data, second table1mapping , third master table.
i want data table1mapping if related data exists otherwise master table , table 1.
table 1 common.
for example:
table 1:
id name 1 abc table1mapping:
table1id country code 1 958 2 ind 89 master
country code uk 87 56 ind 45 user can select multiple countries. if selects , ind code should table1mapping , ind should master there no data id 1 , us.
code may different in both tables.
you didn't provide schema created fantasy data show how can like.
description: use 2 left joins in combination coalesce, give first element not null.
declare @tab1 table ( id int ) declare @tabmapping table ( id int, anycol varchar(100) ) declare @tabmaster table ( id int, anycol varchar(100) ) insert @tab1 (id) values (1),(2),(3),(4),(5),(6) insert @tabmapping (id,anycol) values (1,'a'),(2,'b'),(3,'c') insert @tabmaster (id,anycol) values (3,'c'),(4,'d'),(5,'e') select t1.id, coalesce(map.anycol,mas.anycol,'no data id') @tab1 t1 left join @tabmapping map on t1.id = map.id left join @tabmaster mas on t1.id = mas.id what should care about: if data in mapping , master? if data not in mapping nor master! (in example if nothing found in mapping , master default value ("no data id") shown. if data exist in both tables value come mapping table it's first argument in coalesce()...
Comments
Post a Comment