sql-serverjoinleft-joinnode-mssql

SQL Server: join one table with two table have same names but select all data from table first if available, otherwise from second table


I tried searching this kind of use case on google but did found exact what i was looking so, Need help to reach to specific point by useful answer, docs or any reference

I have this situation: table A has to be joined with table B and table C; B and C have similar columns, so there will be duplicate column names in select part, however give preferences to all the data of tables B if available otherwise show data from table c

For example:

SELECT 
    ae.*, ml.name as name, ml.contact AS contact,
    ve.name AS name, ve.contact AS contact
FROM 
    TABLE ae
LEFT JOIN 
    TABLE ml ON ae.eid = ml.eid
LEFT JOIN 
    TABLE ve ON ae.eid = ve.eid
WHERE
    ae.eid = 1

ml data

eid | name | contact
----+------+--------
1   | xyz  | null

ve data

eid | name | contact
----+------+--------
1   | xyz  | 1

ae data

eid | gender
----+--------
1   | male

I want this result:

eid | gender | name | contact
----+--------+------+--------
1   | male   | xyz  | null

But I am getting this for now:

eid | gender | name | contact | contact
----+--------+------+---------+--------
1   | male   | xyz  | 1       | null

I'm using node-mssql driver for querying SQL Server data.

Thanks,


Solution

  • You must join ve only if there is no matching row in ml and you do it if you add in the ON clause the condition ... AND ml.eid IS NULL.
    Also use COALESCE() to select the columns from ml first and if they don't exist from ve:

    SELECT ae.*, 
           COALESCE(ml.name, ve.name) AS name, 
           COALESCE(ml.contact, ve.contact) AS contact
    FROM ae
    LEFT JOIN ml ON ae.eid = ml.eid
    LEFT JOIN ve ON ae.eid = ve.eid AND ml.eid IS NULL
    WHERE ae.eid = 1
    

    See the demo.
    Results:

    eid gender name contact
    1 male xyz null