我有这个数据库结构:
product: id, name
type: id, name
product_type: id, product_id, type_id
假设我的产品的类型为id:3,5,8,我想选择所有其他类型为id的产品:3,5,8。如果不存在任何类型的产品3,5,8,它应该搜索:(3,5); (3,8); (5,8);
我使用SQLite作为数据库层。
谢谢
答案 0 :(得分: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;
答案 1 :(得分: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