我正在使用MariaDB 10.2.21版
有多行具有重复的user_id(该列之一)。
我想获取每个user_id的首次出现,而不仅仅是user_id,而是与user_id的首次出现相关的所有行。
select
distinct user_id,
from
user_table
where
user_id in (a,b,c,d,e,f,....) and
date = '2020-02-25';
现在,当我尝试添加关联的列时,
EXPLAIN
select
distinct user_id,
ST_X(location) as lng
from
user_table
where
user_id in (a,b,c,d,e,f,....) and
date = '2020-02-25';
它告诉我,我将获得2+百万行...我只有3000个唯一的user_id 我只想获取第一个出现的user_id及其关联位置。
由于我的数据库很大,因此我需要充分利用索引,否则它将损坏。
我的索引是[user_id,date],其中user_id是第一索引,而date是第二索引。
所以我的问题是如何通过使用索引获取唯一的(第一次出现=最上一行)用户信息,因此我的数据库不会中断?
所以如果有
user_id location
1 (123.22, 22.33)
1 (111.22, 22.12)
2 (155.33, 41.23)
2 (160.41, 12.31)
我会得到
user_id location
1 (123.22, 22.33)
2 (155.33, 41.23)
答案 0 :(得分:0)
如果您只有一个位置,请使用聚合:
select user_id, ST_X(min(location)) as lng
from user_table
where user_id in (a,b,c,d,e,f,....) and
date = '2020-02-25'
group by user_id;