问题
My question is very similar to this previous post SQL Query, get a columns if another columns equal to x
The only difference is I am joining two tables and the previous solution does not seem to work. Basically I have two Columns once the tables have been joined. I want all rows of a name, where at least one row for that name has "Shasta" as a location. For example,
Column 1 = Name (From Table 1) Column 2 = Location (From Table 2)
Name | Location
-------------------
Bob | Shasta
Bob | Leaves
Sean | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
Should Return:
Name | Location
--------------------
Bob | Shasta
Bob | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
I tried the solution of the previous post
where x in
(
select distinct x
from table 1
where y like 'Shasta'
)
Unfortunately, it only returned:
Name | Location
--------------------
Bob | Shasta
Dylan | Shasta
回答1:
You are looking for a WHERE EXISTS
clause. As an illustration, let's assume you have the following query:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
You are looking to retrieve all rows in this query where there exists a row in the same query results with that Name
and where Location = 'Shasta'
. Therefore we can use the query as a derived table, match the Name
and look for a Location = 'Shasta'
:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
where exists (
select 1
from
(
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
) x --this is the same as the above query, as a derived table
where x.Name = a.Name --correlate the queries by matching the Name
and x.Location = 'Shasta' --look for the column value in question
)
Granted, you may be able to simplify this query and/or eliminate the derived table in the WHERE EXISTS
clause, depending on the actual schema and what table1
and table2
represent.
回答2:
Simply use EXISTS
to return a row if there exists a row with same name and location Shasta:
select name, location
from tablename t1
where exists (select 1 from tablename t2
where t1.name = t2.name
and t2.locaion = 'Shasta')
回答3:
I think you should do another subquery. I'll call the joinresult joinedTable
as you didn't showed us the statement with which you build the table. But you can just switch the joinedTable
for your statement. Then do
select * from joinedTable where name in (select name from joinedTable where location = 'Shasta');
Result is your wanted: 2x Bob, 3x Dylan
Heres a fiddle for it:
http://sqlfiddle.com/#!9/7584e/3
来源:https://stackoverflow.com/questions/30520964/sql-return-all-rows-where-at-least-one-has-value-y