简体   繁体   中英

How do I only select records in a table that have all the values from another table?

This is a hard question to word, but is pretty simple when explained a little more.

I have two tables: Standard_Test{StandardID int, TestID int} and Test{TestID int}

Standard_Test: http://i51.tinypic.com/2u60ket.png

Test: http://i51.tinypic.com/2bbqxj.png

I need to select a list of StandardID's that have all of the TestID's from the Test table associated to it. In the example above, this query would only select StandardID 5 & 6 because they both have TestID's 1,2,3(all of the TestID's from Test) associated with it.

It sounds simple, but I have not been able to come up with the proper query. Thanks in advanced!

You could try this, it should work:

SELECT DISTINCT st.StandardId
FROM Standard_Test st JOIN Test t
ON st.TestId = t.TestId    
GROUP BY st.StandardId
HAVING COUNT(st.TestId) = (SELECT COUNT(TestId) FROM Test)

This should work for any number of rows in Test. (It assumes that a given TestId only appears once in Test -- it is the primary key, right?)

SELECT st.StandardID
 from Standard_Test st
  inner join Test te
   on te.TestID = st.TestID
 group by st.StandardID
 having count(te.TestId) = (select count(*) from Test)

This is relational division. Google for that term and you should find all the info you need.

The Below Code will Work To find your Requirement. Check it out. Here Tab1 = Standard_Test And tab2 = Test

Declare @Test Int

Declare @Tab table ( Stand int )

Declare @Cur Cursor Set @Cur = CURSOR For Select standardID From tab1 Group by standardID

Open @Cur Fetch Next From @Cur into @Test

WHILE @@FETCH_STATUS = 0
    Begin
        If Exists (Select 1
        From tab2
        Where estID not in (Select testId From tab1 Where StandardID = @Test))
            Begin
                insert into @Tab
                values(@Test)
            End
        Fetch Next
        From @Cur into @Test
    End

Close @Cur DEALLOCATE @Cur

Select * From @Tab

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