I am trying to write a query using the following example tables:
Company
- CompanyID
- Name
- County
CompanyRelation
- ParentCompanyID
- ChildCompanyID
CompanySpecialty
- CompanyID
- Specialty
The CompanyRelation table is used because each company can have many subcompanies under it and each subcompany can have many companies over it.
Ideally, what I want to be able to find is all companies by a certain county and/or by a certain specialty. Now, normally, I would just join Company to CompanySpecialty and filter on those two fields, but here is where it gets tricky: the subcompanies don’t have counties assigned to them, so if I filter on the county, all the subcompanies will be excluded.
If I filter the companies down to a county, I would like to display all subcompanies that are associated to that company, regardless of the fact that the subcompany does not have an address.
To get around this, I have to bring in the CompanyRelation table.
Example data:
CompanyID---Name---County
1-----------ABC----King
2-----------BCD----Pierce
3-----------DEF----NULL
4-----------EFG----NULL
ParentCompanyID---ChildCompanyID
1-----------------1
1-----------------3
2-----------------2
2-----------------4
CompanyID---Specialty
1-----------Vehicles
2-----------Vehicles
3-----------Vehicles
4-----------Vehicles
Using this data, say I want to find all companies in King county that deal with vehicles. In my results, I would expect to see Company 1 and Company 3.
How can I write a query to accomplish this?
The Diagram would be like this (with Company being the primary / parent table, and all others depending on it):
Company Specialty <– Company <– Relationship <– Company –> Company Specialty
Converting it to SQL would be like this: