Search code examples
sqlsql-serverdatabaseprocedures

Multiple records in a table matched with a column


The architecture of my DB involves records in a Tags table. Each record in the Tags table has a string which is a Name and a foreign kery to the PrimaryID's of records in another Worker table.

Records in the Worker table have tags. Every time we create a Tag for a worker, we add a new row in the Tags table with the inputted Name and foreign key to the worker's PrimaryID. Therefore, we can have multiple Tags with different names per same worker.

Worker Table

ID         |   Worker Name    |    Other Information
__________________________________________________________________
1          |   Worker1        | ..........................
2          |   Worker2        | ..........................
3          |   Worker3        | ..........................
4          |   Worker4        | ..........................

Tags Table

ID         |Foreign Key(WorkerID) |    Name
__________________________________________________________________
1          |   1                  | foo
2          |   1                  | bar
3          |   2                  | foo
5          |   3                  | foo
6          |   3                  | bar
7          |   3                  | baz
8          |   1                  | qux

My goal is to filter WorkerID's based on an inputted table of strings. I want to get the set of WorkerID's that have the same tags as the inputted ones. For example, if the inputted strings are foo and bar, I would like to return WorkerID's 1 and 3. Any idea how to do this? I was thinking something to do with GROUP BY or JOINING tables. I am new to SQL and can't seem to figure it out.


Solution

  • This is a variant of relational division. Here's one attempt:

    select workerid 
    from tags
    where name in ('foo', 'bar')
    group by workerid
    having count(distinct name) = 2