Select `id`, `uid`, case when left_leg > right_leg then left_leg
else right_leg end as Max_leg,`date` from
(
SELECT * FROM network t2 where id in (select id from
(select id,uid,`date` from (SELECT * FROM network order by uid,
`date` desc) t4 group by uid) t3) and
(left_leg>=500 or right_leg>=500))t1
想要从每个uid的最新日期中选择网络数据 想要选择left_leg> = 500或right_leg> = 500的数据 想要只选择更大的两条腿(左或右)
整个查询可能存在一些问题,但核心问题与此代码相关
SELECT * FROM network t2 where id in (select id from
(select id,uid,`date` from (SELECT * FROM network order by uid,
`date` desc) t4 group by uid) t3)
我想改进这个查询,因为它会在数据增长时将结果提取得太慢。
答案 0 :(得分:2)
在(uid,date)上添加索引:
ALTER TABLE network ADD INDEX uid_date( uid, date )
尝试类似:
SELECT n.id, n.uid, greatest( n.right_leg, n.left_leg ) as max_leg, n.date
FROM
( SELECT uid,max(date) as latest FROM network
WHERE right_leg>=500 OR left_leg >=500
GROUP BY uid
) ng
JOIN network n ON n.uid = ng.uid AND n.date = ng.latest
答案 1 :(得分:2)
记下你的描述:
示例:
SELECT id, uid, GREATEST(left_leg, right_leg) as max_leg
FROM network
WHERE (uid, `date`) IN (SELECT uid, MAX(`date`)
FROM network
GROUP BY uid)
AND (left_leg > 500 or right_leg > 500)
请注意,这意味着如果uid的最新日期没有一些腿> 500,然后记录将不会显示在结果中。如果你想要腿的最新记录> 500,腿部过滤器必须移入。