Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

Return list of rows if all records exist in another table in sql server

Simple query in theory but I can't get my head around the required syntax, not sure what this type if query is called / how to word it which is making it difficult to google for a solution. SQL Server 2014

I basically want to return a list of user IDs if all of their records exist within another table.

Example

Users


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use join and group by. Assuming you have no duplicates in userrecords (as in your sample data):

select ur.userid
from userrecords ur join
     lookup lu
     on ur.record = lu.id
group by ur.userid
having count(*) = (select count(*) from lookup);

If you do have duplicates in userrecords, then use count(distinct record).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...