Suppose we have 3 tables:
| test1 | | test1_to_test2 | | test2 | |-------+ +----------------| +-------| | id |-----| test1_id | +----| id | | test2_id |----+
It is the structure that you have.
Content:
test1 +----+-------+ | id | value | +----+-------+ | 1 | val1 | | 2 | val2 | +----+-------+ test1_to_test2 |----------+----------| | test1_id | test2_id | |----------+----------| | 1 | 1 | | 1 | 2 | | 2 | 1 | |----------+----------| test2 |----+ | id | |----+ | 1 | | 2 | |----+
And we need to select values ββfrom table test1 that have rows in test1_to_test2 with (test2_id = 1) AND (test2_id = 2). So we want:
+----+-------+ | id | value | +----+-------+ | 1 | val1 | +----+-------+
To do this, we will divide the task into two subtasks:
1.Select test1_id from test1_to_test2, which contains both lines:
SELECT test1_id FROM test1_to_test2 WHERE test1_to_test2.test2_id IN (1,2) GROUP BY test1_id HAVING COUNT(test1_id) = 2
2.Select the appropriate rows from test1 using the subquery and the IN statement (this is the SQL we need):
SELECT test1.id, test1.`value` FROM test1 WHERE test1.id IN ( SELECT test1_id FROM test1_to_test2 WHERE test1_to_test2.test2_id IN (1,2) GROUP BY test1_id HAVING COUNT(test1_id) = 2 )
We get what we need:
+----+-------+ | id | value | +----+-------+ | 1 | val1 | +----+-------+
Use the same approach with your tables, and you will receive messages with the "XYZ" area and the "ABC" kitchen.
source share