我有一个相当疯狂的SQL查询,它可以在MySQL <5.7环境中完美运行:
SELECT
sp.id,
(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) * 25
+
(SELECT COUNT(spt.id) FROM project_task AS spt WHERE spt.project = sp.id AND spt.address = pt.address) * 10
+
(SELECT COUNT(spc.id) FROM project_campaign AS spc WHERE spc.project = sp.id AND spc.campaign = pc.campaign) * 500
+
(SELECT COUNT(sp2.id) FROM project AS sp2 WHERE sp2.id = sp.id AND sp2.category = p.category) * 10
+
(SELECT COUNT(sp3.id) FROM project AS sp3 WHERE sp3.id = sp.id AND sp3.special_category = p.special_category) * 25
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 = :id
AND
sp.is_live = TRUE
GROUP BY
sp.id
ORDER BY
similarity DESC,
sp.created DESC
LIMIT 6
基本上,这是一种基于多个相关表从给定ID中选择6个最相似项目的算法。
不幸的是,在> 5.7环境中运行此命令时,出现以下错误:
Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.pa.attribute' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
如果我在GROUP BY中添加“相似性”,它不会引发错误,但是会提供错误的结果(例如,第一个和第四个结果是相同的条目)。
我还尝试添加“ SELECT DISTINCT sp.id”,但结果中它仍具有相同的项目两次。
是否可以在不更改“ sql_mode = only_full_group_by”的情况下获得与以前相同的结果?