有人可以帮我优化这个查询吗?我有一张包含大量数据的表格。有人可以帮我优化而不使用子查询吗?
SELECT user_id, scheduled_on_date
FROM
(SELECT user_id, scheduled_on_date
FROM `calls`
ORDER BY scheduled_on_date DESC) AS cinner
GROUP BY user_id
预期产出为: 我需要的是用户的唯一行以及上次调度的调用日期。
答案 0 :(得分:1)
您可以按如下方式重写查询
SELECT c.user_id, c.scheduled_on_date ,other_fields_max_per_group
FROM `calls` c
JOIN (SELECT user_id, MAX(scheduled_on_date) scheduled_on_date
FROM `calls`
GROUP BY user_id) AS cc
ON(c.user_id =cc.user_id AND c.scheduled_on_date =cc.scheduled_on_date)
添加化合物索引
ALTER TABLE calls ADD INDEX `test` (user_id ,scheduled_on_date )
如果您只想要最大的日期和用户ID,则只能使用
SELECT user_id, MAX(scheduled_on_date) scheduled_on_date
FROM `calls`
GROUP BY user_id
答案 1 :(得分:0)
select c1.*
from calls c1 left join call c2 on c1.user_id = c2.user_id
and c1.scheduled_on_date < c2.scheduled_on_date
where c2.user_id is null;
如果您想进一步优化