I need to implement following categorization in SQL:
- group can contain multiple tests or multiple (child) groups
- test could be in multiple groups
- (child) group could be in multiple (parent) groups
… that means 2 x M:N relations. Following tables could store the group trees:
TEST_TABLE
test_id (pk), test_name
GROUP_TABLE
group_id (pk), group_name
TEST_IN_GROUP_TABLE
test_id (fk), group_id (fk)
GROUP_RELATIONS_TABLE
parent_group_id (fk), child_group_id (fk)
But:
- How to list all tests in group? This sounds to me impossibly difficult, since group could contain tests or sub-groups with another tests.
- Or how to modify tables to make such SELECT possible? I could create additional child_count column in GROUP_TABLE. It will be auto-filled by trigger. But even with it it’s hard nut for me.
You use Common Table Expressions to first build up the group_ids of the group sought, then using that single list of groups, join through TEST_IN_GROUP_TABLE to the test table for all tests.