2012-01-05 113 views
0

我有3个表Products,ProductHas,Props。不用说,每个产品都有不止一个支柱,保存在ProductHas表中。我试图找到Product B这是最接近Product A他们的道具相似之处。根据具有多对多关系的连接器表查找类似记录

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

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

您需要定义“相似性”多一点严格... – 2012-01-05 13:20:11

+0

@大卫M拥有大部分共同的道具 – Sevki 2012-01-05 13:28:45

+2

无论数量不共同吗? – 2012-01-05 13:33:56

回答

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 
+0

它不能在mysql中运行......从顶部可以看出它对于ms sql可能吗? – Sevki 2012-01-05 15:01:17

+0

删除TOP 1,并在最后替换为LIMIT 1,如果内存正确地为我服务 - 编辑答案... – 2012-01-05 15:03:35

+0

谢谢我已经这样做了,但它会在部件上出现错误,这就是为什么我最终改变了在我的改动之后,它的部分内容看起来像这个https://gist.github.com/1565625,它只返回具有最多道具的产品,而不是大多数共同的道具...... – Sevki 2012-01-05 15:08:26

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 
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 
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); 
相关问题