I'm concerned about performance when performing multiple subqueries (8 to be exact) in a SELECT. When tested, it took approximately 5 seconds to find a result.
Given that I have a database with 3 tables: combinations, groups and subjects.
group_1,group_2,group_3andgroup_4reference anidfromsubjects.subject_idreferences anidfromgroups.
Combinations:
| id | group_1 | group_2 | group_3 | group_4 |
|----|---------|---------|---------|---------|
| 1 | 6 | 4 | 6 | 9 |
| 2 | 3 | 16 | 10 | 5 |
| .. | .. | .. | .. | .. |
Groups:
| id | subject_id | name | max |
|----|------------|------|-----|
| 1 | 2 | 101 | 15 |
| 2 | 2 | 102 | 17 |
| .. | .. | .. | .. |
Subjects:
| id | name |
|----|-----------|
| 1 | "Science" |
| 2 | "Math" |
| .. | .. |
I'm doing the following query to grab an id from combinations given that I know the name of the subjects (i.e. Math, Science, P.E. and Art) and the group (i.e. 101, 102, 104, 101).
SELECT
id
FROM
combinations
WHERE
group_1 = (SELECT id FROM groups WHERE name = $group_name AND subject_id = (SELECT id FROM subjects WHERE name = $subject_name))
AND
group_2 = (SELECT id FROM groups WHERE name = $group_name AND subject_id = (SELECT id FROM subjects WHERE name = $subject_name))
AND
group_3 = (SELECT id FROM groups WHERE name = $group_name AND subject_id = (SELECT id FROM subjects WHERE name = $subject_name))
AND
group_4 = (SELECT id FROM groups WHERE name = $group_name AND subject_id = (SELECT id FROM subjects WHERE name = $subject_name))
Is there any way to optimize the performance? I thought of trying with INNER JOIN, but didn't know how to structure the query.
if I understand your tables and data correctly, your subqueries are testing twice the same thing (name = 101 and name = 'Math'). As a first step, you could replace the subqueries by e.g.
However, this will probably not improve the performance. The main issue with the performance is that you still need to join the table combinations 4 times with at least one table (groups). Reorganizing the data in another structure would be a better option.