MySQL子查询仅从JOIN表中获取最新值

时间:2017-12-01 14:39:11

标签: mysql

我有以下MySQL查询。 user_extra表可以返回给定user_id的多个值。我只想从user_extra获得最新的a.session_date值。

foreach()

我有什么想法可以做到这一点吗?

3 个答案:

答案 0 :(得分:0)

一种方法是加入查询最新记录的子查询。这可能是最好的方法,因为MySQL没有可用的分析功能。在这种情况下,我们可以向您的查询添加一个连接,以限制user_extra表使记录对应于每个用户的最近会话。

SELECT
    ur.user_id,
    ue1.value
FROM user_reg ur
INNER JOIN user_extra ue1
    ON ur.user_id = ue1.user_id AND
       ue1.session_date <= '2017-01-01'
INNER JOIN
(
    SELECT user_id, MAX(session_date) AS max_session_date
    FROM user_extra
    GROUP BY user_id
) ue2
    ON ue1.user_id = ue2.user_id AND
       ue1.session_date = ue2.max_session_date
WHERE
    ur.session_date BETWEEN '2017-01-01' AND '2017-06-10';

答案 1 :(得分:0)

如果您想获得用户使用的所有值的列表:

SELECT A.user_id, GROUP_CONCAT(B.value) LIST_OF_VALUES FROM
(SELECT user_id, value FROM user_reg 
WHERE session_date BETWEEN '2017-01-01' AND '2017-06-10'
GROUP BY user_id, value) A INNER JOIN
(SELECT user_id, MAX(session_date) FROM user_extra 
WHERE session_date<='2017-01-01' GROUP BY user_id) B
ON A.user_id=B.user_id
GROUP BY A.user_id;

但是如果你想获得用户的总价值:

SELECT A.user_id, SUM(B.value) SUM_OF_VALUES FROM
(SELECT user_id, value FROM user_reg 
WHERE session_date BETWEEN '2017-01-01' AND '2017-06-10'
GROUP BY user_id, value) A INNER JOIN
(SELECT user_id, MAX(session_date) FROM user_extra 
WHERE session_date<='2017-01-01' GROUP BY user_id) B
ON A.user_id=B.user_id
GROUP BY A.user_id;

答案 2 :(得分:0)

select ap.user_id, ap1.value
from user_reg ap
inner join (
    select user_id, max(session_date) as MaxDate, value
    from user_extra 
    group by user_id
) ap1 on ap.user_id = ap1.user_id and ap.date = ap1.MaxDate

它将为单个用户ID提供最大会话日期。