Consider a db with 2 tables like below. CompanyId is a foreign key in Department table pointing to Company. Company names are unique but the department names are not.
Table : Department
+-------+-----------+-----------+-------------------+
| id | name | CompanyId | phone |
+-------+-----------+-----------+-------------------+
| 1 | Sales | 1 | 214-444-1934 |
| 2 | R&D | 1 | 555-111-1834 |
| 3 | Sales | 2 | 214-222-1734 |
| 4 | Finance | 2 | 817-333-1634 |
| 5 | Sales | 3 | 214-555-1434 |
+-------+-----------+-----------+-------------------+
Table : Company
+-------+-----------+
| id | name |
+-------+-----------+
| 1 | Best1 |
| 2 | NewTec |
| 3 | JJA |
+-------+-----------+
I have a filter like below. when department name is null (empty) it means all the department id for that company should be included in the result but when there is list it should only include the ones which are listed.
[ {
companyName: "Best1",
departmentName: ["Sales", "R&D"]
},
{
companyName: "NewTec",
departmentName: ["Finance"]
} ,
{
companyName: "JJA",
departmentName: null
}
}]
Note: The filter is dynamic (a request to an API endpoint) and may include thousands of companies and departments.
I want a sql query to return all department id which fits in the criteria. for this example the result would be "1,2,4,5". (all department ids except the NewTec Sales department's id (3) are returned)
I'm looking for efficient SQL and/or linq query to return the result. I can loop through companies and filter out departments for each individual one but it means that for each company there would be one trip to database using an ORM. Is there any better way to handle this case?