首页 > 解决方案 > 仅选择 JOIN 语句中的最后一条记录

问题描述

我有以下查询:

    SELECT 
      usp.user_id AS userId,
      usp.create_time AS create_time,
      ml.amount AS amount      
    FROM user_subscription_plan AS usp
            RIGHT JOIN product AS product ON product.id = usp.product_id            
            LEFT JOIN modification_log AS ml ON ml.subscription_id = usp.id         
    WHERE usp.id IN ('447482')

我有三个表,我需要从中选择数据。

我的问题从最后一个 LEFT 加入开始。

modify_log 表可以没有条目,但也可以有更多条目。我只想选择最新的条目。使用上述查询,如果我在 modify_log 中有 2 个(或更多)条目,我会收到 2 个相同的结果(重复)。

我想得到什么:

如果 modify_log 中没有结果,则返回 null。我认为 LEFT JOIN 涵盖了这一点。而且,在很多记录的情况下,我需要选择最近添加的一个(数量)

我相信我可能需要一个子查询,但我没有实现它。

标签: mysql

解决方案


您必须使用子查询将左连接与 modify_log 表作为

SELECT 
  usp.user_id AS userId,
  usp.create_time AS create_time,
  ml.amount AS amount      
FROM user_subscription_plan AS usp
  RIGHT JOIN product AS product ON product.id = usp.product_id            
  LEFT JOIN 
        (select * modification_log where subscription_id 
        IN ('447482') order by created_at desc LIMIT 1)
        AS ml ON ml.subscription_id = usp.id         
WHERE usp.id IN ('447482')

请注意,子查询中的 where 子句select * modification_log where subscription_id IN ('447482') 与最后一个 where 条件相同


推荐阅读