mysql - 仅选择 JOIN 语句中的最后一条记录

标签 mysql

我有以下查询:

    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 连接。

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

我想要得到什么:

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

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

最佳答案

您必须使用子查询将与modification_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 * revision_log where subscription_id IN ('447482') 与最后一个where条件相同

关于mysql - 仅选择 JOIN 语句中的最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55633009/

相关文章:

mysql - 如何在 JSF 的 inputMask 中传递特定格式的 dateTime 参数?

mysql - 将 mysql 转储导入新的 Redmine 实例时出现未知列 'tokens.update_on'

mysql 比较相似字符串的函数

MySQL SUM() 与 COUNT() 在多列上

php - UPDATE mysqli_query() 的正确语法/方法

MySQL - 如果在事务期间插入失败,是否总是会引发异常或警告?

php - 将 2 个 select mysql base 合二为一

mysql - 安装drupal时无法连接远程数据库

mysql - 如何获得 2 列的不同计数值?

php - MySQL 中的 CakePHP 错误日期