September 9, 2009 at 1:24 pm
Hi,
I need a SQL query that will do this:
SELECT * FROM Table1 T1
WHERE T1.column1 IN (SELECT column1 FROM Table2)
AND T1.column2 IN (SELECT column2 FROM Table2)
eg.
SELECT * FROM Employees T1
WHERE T1.Name IN (SELECT Name FROM Students)
AND T1.Age IN (SELECT Age FROM Students)
Basically, both of inner queries do the same thing but return different column values. What would be the best way to write this query?
September 9, 2009 at 7:48 pm
[Edit] Read that a bit too quickly the first time.
The way you are doing it should work. Perhaps if you share your end goal, we can come up with a different way of going about getting there.
September 9, 2009 at 8:47 pm
The current query (either one) will return all employees who's name and age are in the student table.... they just might not be on the same row, though because there is no correlation between the two sub queries via the outer query.
Why wouldn't you just use a single inner join with two criteria for this?
--Jeff Moden
Change is inevitable... Change for the better is not.
September 9, 2009 at 8:52 pm
Like this...
SELECT e.*
FROM dbo.Employees e
INNER JOIN dbo.Students s
ON e.Name = s.Name
AND e.Age = s.Age
--Jeff Moden
Change is inevitable... Change for the better is not.
September 9, 2009 at 9:05 pm
Jeff Moden (9/9/2009)
Like this...
SELECT e.*
FROM dbo.Employees e
INNER JOIN dbo.Students s
ON e.Name = s.Name
AND e.Age = s.Age
That's what I edited back out when I reread it. Should have left it tho, maybe the lack of correlation was unintentional, as you suggest.
September 9, 2009 at 9:31 pm
Heh... I figured. If it helps, I almost did the same thing until I realized there was no correlation between the sub-queries.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply