简体   繁体   中英

How to select and sub-select from 2 tables?

Suppose I have 2 tables as below:

Table1:

variable    value
--------------------------------------------
app1        name@email.com, name2@email.com
app2        name3@email.com, name4@email.com

Table2:

app DatabaseName    server
---------------------------
app1    DB1        server1
app1    DB1        server2
app2    DB2        server1
app2    DB2        server3

I want to select the the email recipients from the value column in Table1 for which DatabaseName is 'DB1' in Table2.

The expected results are: name@email.com, name2@email.com.

How can I do that?

Basically the tricky part here is that the column name is not "app" in Table1, but rather "variable". It is the requirement that way, So how do I achieve selecting email recipients for a databaseName based on the classified app the DatabaseName belongs to in Table2 and matches in Table1?

You just need to do a join.

SELECT DISTINCT T1.[value] 
FROM Table1 T1 INNER JOIN Table2 T2 
ON T1.[variable] = T2.[APP] 
WHERE T2.DatabaseName = 'DB1'

You need to join the tables:

select distinct t1.*
from table1 t1 inner join table2 t2
on t2.app = t1.variable
where t2.databasename = 'DB1'

I used distinct because from your sample data there are 2 rows for databasename = 'DB1' and otherwise you would get the same row twice.

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