简体   繁体   中英

get output from two tables(table A and b) if column A from table A is equal to column B from Table B

So I have two tables A and B, both tables have a column address. Table A has id1 column and Table B has id2 column. I would like to get the address column (it can be table B) if the values in id1 and id2 columns are the same. How can I do that in sql command? It's worth to mention if these columns are the same, the addresses will be the same too or similar, so the address can be from either table. I'm very new to sql and your help will be much appreciated. Thanks in advance

You should try this:

Select address 
from tablea as a, table b as b 
where b.id =a.id

I'm assuming there's a chance that the address in table 1 is missing, otherwise it'd just be a matter of selecting that field. I added a case statement to handle that just in case (heh), but if not you can just replace that whole bit with a.address

Select a.id1, 
     case when a.address is not null 
        then a.address 
        else b.address end as new_address.
from Table1 A, Table2 B
where a.id1 = b.id2

Additionally, if you've got a combination of inner and outer joins happening (or just a lot of joins) then you'll want to add more explicit join criteria.

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