简体   繁体   中英

return one table from two tables where condition exists in one or the other

This is a little weird, but I need to select from one of two tables that have a given unique identifier. Let's say that table A looks like:

ID CallNumber Caller

and table B looks like:

ID CallNumber Caller

and I have a unique identifier that could be in either one. How could I write a select statement that would return these columns and display the data from either table A or table B? What I have come up with so far is:

SELECT 
coalesce(a.ID,t.id) as ID
,coalesce(a.CallNumber,t.CallNumber) as CallNumber
,coalesce(a.Caller,t.Caller) as Caller
FROM tableA a
right join  tableB b on b.ID = a.ID
where a.ID = '' or b.ID = ''

but this will only return the unique identifier if the ID lives in table A.

If it needs to be one query then you could query both tables and mash up the results. You don't need to bother with joining tables or other logic.

select
    ID,
    CallNumber,
    Caller
from
    tableA
where
    ID = theID

union all -- adding 'all' avoids unnecessary sorting operation

select
    ID,
    CallNumber,
    Caller
from
    tableB
where
    ID = theID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM