基于具有多对多关系的连接器表查找类似记录

时间:2012-01-05 13:18:40

标签: mysql sql

我有3张桌子Products,ProductHas,Props。毋庸置疑,每个产品都有多个支柱保存在ProductHas表中。我试图找到最接近Product B道具相似之处的Product A

表格的当前结构如下所示。

+----------+----------+-----------+
|Products  |ProductHas|Props      |
+----------+----------+-----------+
|product_id|product_id|prop_id    |
+----------+----------+-----------+
|   name   | prop_id  |description|
+----------+----------+-----------+

4 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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

答案 1 :(得分:0)

另一个选择

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

答案 2 :(得分:0)

尝试:

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

答案 3 :(得分:0)

您可以在道具表上尝试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);