从每个user_id获取来自Deals_public表格的最新记录

时间:2020-10-03 12:31:10

标签: mysql sql inner-join

这是我的查询

select
    users.id as user_id,
    users.cat as cat,
    from_currencies.id as from_currency,
    to_currencies.id as to_currency,
    deals_public.change_from as change_from,
    deals_public.change_to as change_to,
    users.site as link,
    users.username as user_name,
    users.email as email,
    users.active as active,
    from_currencies.name as from_name,
    from_currencies.sign as from_sign,
    to_currencies.name as to_name,
    to_currencies.sign as to_sign
 from
     `deals_public`
 inner join `users` on `users`.`id` = `deals_public`.`user_id`
 inner join `currencies` as `from_currencies` on `from_currencies`.`id` = `deals_public`.`from_currency`
 inner join `currencies` as `to_currencies` on `to_currencies`.`id` = `deals_public`.`to_currency`
 where
    `users`.`active` = 1
     and from_currency like '34'
     and to_currency like '35'
 limit
     20

我在deals_public表中有一列名为register的列,该列保存created_at的时间戳,我想基于user_id获取最新的行。 我的意思是,我只想为每个user_id从Deals_public中获取一条记录

编辑:

我通过使用以下方法来工作:

group by user_id

但是此查询花费的时间太长(15秒)

我该如何减少时间?

2 个答案:

答案 0 :(得分:0)

您只需要添加一个条件,例如

and not exists (select 1 from deals_public dp where dp.register > deals_public.register and deals_public.user_id = deals_public.user_id)

因为这正是您想要的:不存在针对该用户的更新的公共交易。

答案 1 :(得分:0)

如果您正在运行MySQL 8.0,则可以为此使用窗口函数。

我将其表达为:

select
    u.id as user_id,
    u.cat as cat,
    fc.id as from_currency,
    tc.id as to_currency,
    dp.change_from as change_from,
    dp.change_to as change_to,
    u.site as link,
    u.username as user_name,
    u.email as email,
    u.active as active,
    fc.name as from_name,
    fc.sign as from_sign,
    tc.name as to_name,
    tc.sign as to_sign
from (
    select dp.*, row_number() over(partition by user_id order by register desc) rn 
    from deals_public
    where from_currency = 34 and to_currency = 35
) dp
inner join users u on u.id = dp.user_id
inner join currencies as fc on fc.id = dp.from_currency
inner join currencies as tc to_currencies on tc.id = dp.to_currency
where dp.rn = 1 and u.active = 1 
limit 20

理论上:

  • 想法是用deal_public枚举row_number()中每个用户的行,然后使用该信息过滤外部查询

  • 我们还可以在from_currenciesto_currencies上对该表进行预过滤,这可以提高查询效率;我将like条件更改为相等条件(在正确的操作数内没有通配符,两者都是等效的)-看起来它们是数字,因此将它们进行比较

  • 表别名使查询更易于编写和读取