因此,在善良的 SO 用户的一点帮助下,我最终得到了一个逻辑上正确的 MySQL 查询,用于我正在处理的一项任务:为用户允许的新闻项目检索一个按时间顺序排列的 id 列表,使用某些类型的分组项目过滤到该组的单个代表。(呸!)
剩下的明显问题是这个查询非常笨拙和缓慢 - 根据 CakePHP 的数据库调用调试打印输出,调整到 145000 毫秒,哎呀。
有没有一种明智的方法来驯服像这样的野兽,或者我应该承认我在这里咬得比我能咀嚼的更多,并寻找一种不那么笨重的方法来获得或多或少相似的结果?所有建议表示赞赏。
SELECT DISTINCT Uid.id, Uid.type
FROM (SELECT uids.id id, uids_uids.parent_id parent_id, uids.created date,
uids.type type
FROM uids
JOIN uids_uids ON uids_uids.uid_id = uids.id
JOIN aros_uids ON uids.id = aros_uids.uid_id
JOIN uids_uids ParentUids ON uids_uids.parent_id = ParentUids.uid_id
WHERE uids.type IN ('Document','Photo','Release','PreRelease',
'ArtworkResource','Event')
AND (uids.start_date IS NULL OR uids.start_date <= NOW())
AND (uids.end_date IS NULL OR uids.end_date <= NOW())
AND aros_uids.aro_id IN (3,2,86,1448)
) Uid
JOIN (SELECT uids_uids.parent_id parent_id, MAX(uids.created) maxdate
FROM uids JOIN uids_uids
ON uids_uids.uid_id = uids.id
GROUP BY uids_uids.parent_id, uids.type) T2
ON Uid.parent_id = T2.parent_id AND Uid.date = T2.maxdate
ORDER BY Uid.date DESC
LIMIT 100
预计到达时间:
好的,作为第一遍,我将这些子选择转换为视图,所以现在查询看起来更易于管理
SELECT DISTINCT Uid.id, Uid.type
FROM UidView Uid
JOIN UidView2 T2
ON Uid.parent_id = T2.parent_id AND Uid.date = T2.maxdate
WHERE Uid.aro_id IN (3,2,86,1448)
ORDER BY Uid.date DESC
LIMIT 100
这肯定有帮助,将 Cake 的估计查询时间(毫秒)从六位数减少到 2500 左右。绝对是一个好的开始!