Well, that's pretty vague information and poor names for tables/columns. But assuming that "T2" holds a list of items that should be shown in "T3" (excluding items not in "T2"), this query should do it:
SELECT T1.col1, T1.col2, T1.col3, T1.col4, T1.col5, T1.col6
FROM T1
INNER JOIN T2 ON T2.col3 = T1.col5
I'm using a join because I believe the database engine will work fastest that way at excluding rows that don't match with "T2". A more logical way of doing it would be either:
SELECT col1, col2, col3, col4, col5, col6
FROM T1
WHERE EXISTS (SELECT * FROM T2 WHERE T2.col3 = T1.col5)
or this one (most likely slower):
SELECT col1, col2, col3, col4, col5, col6
FROM T1
WHERE col5 IN (SELECT col3 FROM T2)
zhj
November 13th, 2007, 03:01 PM
thank you for your suggestions. I tried it but gave me a blank output. basically, i need to add the first two columns of #temp2 to #temp1 and keep only those rows in #temp1 that are in #temp2 (like above T3). i tried to use "select *" from two tables and gave an output but was not right. i tried the following stored procedure. but no luck.
/*
SELECT t1.col1, t1.col2, t1.col3, t1.col4, t1.col5, t1.col6
FROM #temp1 as t1
INNER JOIN #temp2 as t2 ON t2.col3 = t1.col5 */
/*
SELECT t1.col1, t1.col2, t1.col3, t1.col4, t1.col5, t1.col6
FROM #temp1 as t1
WHERE EXISTS (SELECT * FROM #temp2 as T2 WHERE T2.col3 = t1.col5) */
SELECT t1.col1, t1.col2, t1.col3, t1.col4, t1.col5, t1.col6
FROM #temp1 as t1
WHERE col5 IN (SELECT col3 FROM #temp2 as t2)
DROP TABLE #temp2
DROP TABLE #temp1
GO
zhj
November 13th, 2007, 11:46 PM
andreasblixt, thank you for your helpful answer. I made a tiny bit adjustment to your solution and works fine. thanks.
andreasblixt
November 14th, 2007, 02:39 AM
May I ask what adjustments you made? I tried your queries above exactly as they stand, with the exception of not putting them in a stored procedure but rather running them as separate batches (first I created #temp1 and #temp2, then I ran the queries one by one), and I got the expected result set of four rows for all three of them.
zhj
November 14th, 2007, 03:36 PM
maybe it was my wrong when i tried the procedure. I did not get the A B A B column. that was all missing. i had to add the t2b.col1, t2b.col2 to your query in order to get that A B A B column. thanks again for the help.
andreasblixt
November 15th, 2007, 02:33 AM
Oh, that's right, I didn't see you wanted to include those columns as well, sorry.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.