2014-02-12 39 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;