gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:34:54 25 4
gpt4 key购买 nike

我有以下查询:

    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 * modification_log where subscription_id IN ('447482')与最后一个where条件相同

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com