Hello,
I have two (example) tables here A) data_table
:
+----------+-------+
| location | value |
+----------+-------+
| 43 | 38 |
| 44 | 31 |
| 3 | 31 |
| 11 | 38 |
| 47 | 35 |
| 49 | 31 |
| 50 | 31 |
| 55 | 16 |
| 56 | 16 |
| 59 | 35 |
| 42 | 35 |
+----------+-------+
and B) neighbour_table
:
+-----------+-----------+
| location1 | location2 |
+-----------+-----------+
| 43 | 3 |
| 43 | 11 |
| 43 | 55 |
| 3 | 50 |
| 3 | 16 |
| 49 | 56 |
| 49 | 42 |
+-----------+-----------+
I would like to select the locations
with same value
as at least one of their neighbour has. What is the best way to do this (according to performance)?
So far I tried this:
1) Select all locations with value which is present more than once in the table:
SELECT location,value FROM data_table
WHERE value IN
(SELECT value FROM data_table GROUP BY value HAVING COUNT(value) > 1);
2) Now I would like to filter the result using the neighbour_table
, but how? Using JOIN
? Or another derived table (subquery)?
I think about using PHP to do the job, but how about the performance? Anyway I would like to see the SQL solution if there is one.
Thanks in advance