2017-03-28 58 views
0

我有以下實體:排序基於關係表「最佳匹配」值

Project 

擁有多個相關表:

Project >-<ProjectAttribute>-< AttributeType 
Project >-<ProjectAttribute>-< AttributeValue 
Project >-<ProjectTask>------< Task 
Project >-<ProjectTask>------< Employee 
... 

涉案金額約15桌,包括subjoins。

現在我需要通過比較值和計算出現次數,爲給定的單個項目找到最匹配的項目。例如AttributeType和AttributeValue的匹配將項目的「最佳匹配」指標增加1.

我該如何實現這一目標?

回答

0

我想我找到了如何查詢相似之處:

SELECT 
    sp.*, 
    ((
     SELECT COUNT(spa.id) FROM project_attribute AS spa WHERE spa.project = sp.id AND spa.attribute = pa.attribute AND spa.attribute_value = pa.attribute_value 
    ) * 1) 
    + 
    ((
     SELECT COUNT(spt.id) FROM project_task AS spt WHERE spt.project = sp.id AND spt.address = pt.address  
    ) * .25) 
    + 
    ((
     SELECT COUNT(spc.id) FROM project_campaign AS spc WHERE spc.project = sp.id AND spc.campaign = pc.campaign 
    ) * 2) 
    AS similarity 
FROM project AS p 
LEFT JOIN project_attribute AS pa ON (p.id = pa.project) 
LEFT JOIN project_task AS pt ON (p.id = pt.project) 
LEFT JOIN project_campaign AS pc ON (p.id = pc.project) 
LEFT JOIN project AS sp ON (p.id != sp.id) 
WHERE 
    p.id = <PROJECT-ID> 
GROUP BY sp.id 
ORDER BY 
    similarity DESC 

我還添加了一個乘數,控制類似的行的影響。

性能不是最好的(235個項目約200ms),但它符合我目前的需求。