2014-02-12 40 views
0

我有这样的数据库结构:SQL按相关性选择 - 多对多

product: id, name 
type: id, name 
product_type: id, product_id, type_id 

假设我有一个具有类型的ID的产品:3,5,8,我想选择其他所有的产品,如果没有任何类型3,5,8的产品,它应该搜索:(3,5); (3,8); (5,8);

我使用SQLite作为db层。

谢谢

+0

我没有任何ideea。我一直在想做一个子查询... ORDER BY(子查询),为了排序,在这个子查询中,我可以选择所有其他有ID的产品:3,5,8 - 但我不知道如何选择那些只有3,5的产品;或者5,8 ... –

+0

您是否想要获得最接近初始产品的一种产品? – user2989408

+0

是的,这是我想要的.. –

回答

1

试试这个,这也应该起作用。

SELECT 
    p.name 
FROM product p 
    JOIN product_type pt ON p.id = pt.product_id 
WHERE pt.typeid IN (3, 5, 8) /*You can use a sub query to select the types*/ 
GROUP BY p.name 
ORDER BY COUNT(pt.type_id) DESC 
LIMIT 1 
1

如果你知道的三种类型,那么你可以做:

select pt.product_id 
from product_type pt 
where product_id <> MYPRODUCTID 
order by ((case when type_id = 3 then 1 else 0 end) + 
      (case when type_id = 5 then 1 else 0 end) + 
      (case when type_id = 8 then 1 else 0 end) 
     ) desc 
limit 1; 

如果你不这样做,你可以指望的比赛:

select pt.product_id 
from product_type pt join 
    product_type psone 
    on pt.type_id = ptone.type_id and 
     ptone.product_id = MYPRODUCTID and 
     pt.product_id <> MYPRODUCTID 
group by pt.product_id 
order by count(*) desc 
limit 1;