I've three tables like follows:

items

id   |   name
1    |   name1
2    |   name2
3    |   name3

characteristics

id   |    name    
1    |      attr1
2    |      attr2
3    |      attr3
4    |      attr4
5    |      attr5
6    |      attr6
7    |      attr7

attr_rel Helps make the relationship between prodcuts and characteristics

attr_id   |  prod_id
   1      |      1
   1      |      2
   2      |      1
   2      |      2
   3      |      3
   4      |      2
   4      |      3
   5      |      1
   5      |      2
   5      |      3

Things I want is to carry out a query that returns all items purchased by the amount of characteristics they share having a given product.

Example: For product 3 query should return something similar to

id    |    name     |    num_attr_in_common
2     |  product2   |             2
1     |  product1   |             1

(Because product 3 shares characteristics 4 and 5 with product 2 only share attribute 5 with product 1)

Can anybody produce an help please?

select a1.prod_id,p.name,count(*) as num_attr_in_common
from attr_rel as a1
inner join (
select attr_id
from attr_rel
where prod_id = 3) as a2
on a1.attr_id = a2.attr_id and a1.prod_id <> 3
inner join products as p on p.id = a1.prod_id
group by a1.prod_id
order by num_attr_in_common desc