views:

34

answers:

1

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

+1  A: 

You could use a join to look up the value for both neighbours. Then you can select neighbours with the same value using a where clause:

select     n.*
from       neighbour_table n
join       data_table d1
on         d1.location = n.location1
join       data_table d2
on         d2.location = n.location2
where      d1.value = d2.value
Andomar
That's it? That's pretty simple! Shame I didn't realize that :-)Thank you very much.
Petr Peller