mysql - 仅选择 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 涵盖了这一点。而且,在很多记录的情况下,我需要选择最近添加的一个(数量)
我相信我可能需要一个子查询,但我没有实现它。
解决方案
您必须使用子查询将左连接与 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 条件相同
推荐阅读
- docker - 无法移除已停止的 Docker 容器
- java - Maven 不会在 jenkins(linux) 上获取资源
- css - 如何在 video.js 播放器中禁用框阴影和边框
- ssl - 错误 488 此处不可接受
- php - CodeIgniter BMI 计算器不工作
- ruby-on-rails - rails - 获取模型保存的 SQL
- mayavi - 在 mayavi 中沿流线检索值
- ruby-on-rails - 亚马逊 ec2 t2micro 实例上的 Elasticsearch
- r - 使用 R 在 GLM 回归中运行所有可能的交互
- angular - 当我是 Observable.interval 时如何允许函数 sortbydate()