根据具有多对多关系的连接器表查找类似记录
问题描述:
我有3个表Products,ProductHas,Props
。不用说,每个产品都有不止一个支柱,保存在ProductHas
表中。我试图找到Product B
这是最接近Product A
他们的道具相似之处。根据具有多对多关系的连接器表查找类似记录
表格的当前结构如下所示。
+----------+----------+-----------+
|Products |ProductHas|Props |
+----------+----------+-----------+
|product_id|product_id|prop_id |
+----------+----------+-----------+
| name | prop_id |description|
+----------+----------+-----------+
答
尝试这样:
SELECT B.product_id
FROM Products B
INNER JOIN
ProductHas HB
INNER JOIN
ProductHas HA
INNER JOIN
Products A
ON HA.product_id = A.product_id
ON HA.prop_id = HB.prop_id
AND HA.product_id != HB.product_id
ON B.product_id = HB.product_id
WHERE A.product_id = xxx
GROUP BY B.product_id
ORDER BY COUNT(A.product_id) DESC
LIMIT 1
答
另一种选择
SELECT A.Name, B.Name, COUNT(*)
FROM (
SELECT p.name, pp.description
FROM Products p
INNER JOIN ProductHas ph ON ph.product_id = p.product_id
INNER JOIN Props pp ON pp.prop_id = ph.prop_id
) AS A INNER JOIN (
SELECT p.name, pp.description
FROM Products p
INNER JOIN ProductHas ph ON ph.product_id = p.product_id
INNER JOIN Props pp ON pp.prop_id = ph.prop_id
) AS B ON B.description = A.Description
WHERE A.Name = 'A'
GROUP BY
A.name, B.Name
ORDER BY
COUNT(*) DESC
答
尝试:
select h1.product_id, count(h0.prop_id) count_matches, count(*) total_props
from ProductHas h1
left join ProductHas h0
on h0.product_id = ? and h0.prop_id = h1.prop_id and h0.product_id <> h1.product_id
group by h1.product_id
order by 2 desc
limit 1
答
你可以尝试在道具表fulltext
指数,我
CREATE TABLE Props(
prop_id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
description TEXT,
FULLTEXT (description)
) ENGINE=MyISAM;
(我不知道该说明的大小事情,但如果你知道它的极限,那么你应该把它像description VARCHAR(200)
)
SELECT *
FROM Props prod_a_props,
Props prod_b_props,
ProductHas prod_a_rel
WHERE prod_a_rel.product_id = :your_product_A_id
AND prod_a_props.prop_id = prod_a_rel.prop_id
AND MATCH (prod_b_props.description) AGAINST (prod_a_props.description);
您需要定义“相似性”多一点严格... – 2012-01-05 13:20:11
@大卫M拥有大部分共同的道具 – Sevki 2012-01-05 13:28:45
无论数量不共同吗? – 2012-01-05 13:33:56