我有以下查询:
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/