drwn65609 2017-04-04 06:39
浏览 87
已采纳

MYSQL - 获取用户和最新购买数据

I am trying to do a MYSQL query where I get the most recent purchase for a user and then see if falls within certain criteria. Here is the query I put together:

select
    users_purch.purch_date as purchase_date,
    users_purch.total_amount as purchase_amount,
    users.* 
from
    users 
left join
    (
        select
            max(date) as purch_date,
            user_id,
            total_amount 
        from
            users_purchases 
        group by
            user_id
    ) as users_purch 
        on users_purch.user_id = users.id 
where
    users_purch.purch_date < '2016-11-01' 
    and users_purch.total_cost < 112.49 
order by
    users_purch.purch_date desc

It seems that the query works but fails in certain aspects. For example, if a user has more than one purchase entry it is getting the max date but the amount as total_cost that the query retrieves is not from the same row as the max date. How can I rewrite this query to give me the most recent purchase record in its entirety?

Thanks!

  • 写回答

3条回答 默认 最新

  • douji2520 2017-04-04 06:47
    关注

    You have to join once more to user_purchases table in order to get the information about the date:

    select
        users_purch.purch_date as purchase_date,
        users_purch.total_amount as purchase_amount,
        users.* 
    from
        users 
    left join
        (
            select
                max(date) as purch_date,
                user_id
            from
                users_purchases 
            group by
                user_id
        ) as users_purch 
            on users_purch.user_id = users.id 
    left join
       (
           select
              user_id,
              date,
              total_amount
           from
              users_purchases
       ) as users_purch2 on users_purch.user_id = users_purch2.user_id and
            users_purch2.date = users_purch.purch_date
    where
        users_purch.purch_date < '2016-11-01' 
        and users_purch.total_cost < 112.49 
    order by
        users_purch.purch_date desc
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大