我有以下实体:
Project
拥有多个相关表格:
Project >-< ProjectAttribute >-< AttributeType
Project >-< ProjectAttribute >-< AttributeValue
Project >-< ProjectTask >------< Task
Project >-< ProjectTask >------< Employee
...
涉及约15个表,包括子连接。
现在我需要通过比较值和计算出现次数来为单个项目找到最匹配的项目。例如AttributeType和AttributeValue的匹配增加了#34;最佳匹配&#34; 1项目的指标。
我怎样才能做到这一点?
答案 0 :(得分: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个项目约200毫秒),但它符合我目前的需求。