1

I have a table Record (id, name). Then I have 10 different Method tables in each one there are few sub-methods.

So my tables look like:

One:

Record (id, name)
1, abc
2, fgt
3, ght

Two:

Method A (id, rec_id, meth_name)
1, 3, sub1_metha
2, 3, sub2_metha
3, 2, sub1_metha
4, 1, sub3_metha
....

Three:

Method Z,(id, rec_id, meth_name)
1, 2, sub1_methz
2, 1, sub4_methz
3, 2, sub3_methz
4, 3, sub1_methz

User needs to be able to search by sub_methods with either AND or ANY operand.

I need to create 2 queries:

  1. To select all records that have all submethods specified by user.
  2. To select all records that have any submethods specified by user.

I feel like I'm missing something very obvious here (UNION, JOIN, 10 SELECTs)?

Victoria B
  • 79
  • 7

1 Answers1

1

If you really have similar information in ten different tables, then your database design is a bit weak. Perhaps you should have only one table for sub_methods and have an additional column to distinguish between them:

Method (id, rec_id, type, meth_name)
1, 3, A, sub1_metha
2, 3, A, sub2_metha
3, 2, A, sub1_metha
4, 1, A, sub3_metha
....
1, 2, Z, sub1_methz
2, 1, Z, sub4_methz
3, 2, Z, sub3_methz
4, 3, Z, sub1_methz

But with the design you have, you should go ahead and join the record table with the union of all method tables. Then you can add the user query in the WHERE either using OR or AND, depending on which mode the user wants:

SELECT * FROM record
INNER JOIN (
SELECT id, rec_id, 'A' as type, meth_name FROM Method_A
UNION
SELECT id, rec_id, 'Z' as type, meth_name FROM Method_Z
) methods on record.id = methods.rec_id
WHERE ...;

EDIT (alternative solution using a database view):

As suggested by Gudgip: If you already have your table structure and cannot change it anymore, you can create a VIEW to simplify the above query (and potentially other queries). To do this execute this statement once:

CREATE VIEW all_methods AS 
SELECT id, rec_id, 'A' as type, meth_name FROM Method_A
UNION
...
UNION
SELECT id, rec_id, 'Z' as type, meth_name FROM Method_Z;

As a result you get an "alias" for this construct at database level and your search-query can be written as

SELECT * FROM record
INNER JOIN all_methods on record.id = all_methods.rec_id
WHERE ...;
Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35