比较两个表中的分数,并显示最近的不同之处

7ivaypg9  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我在mariadb中有两个表,我需要在左边的表中显示那些当前的分数与历史表中最近的分数不同的表。
例如:

users

id name    current_score
1  Bob     4
2  Tom     5
3  Fred    3
4  Tim     3
5  Ian     4

histories
id user_id score date 
1  1       3     2018-11-13
2  1       4     2018-11-12
3  1       2     2018-11-11
4  2       5     2018-11-12

在上面我想显示鲍勃,因为他最近的历史是不一样的,他目前的分数,但不显示汤姆,因为他是一个匹配
我试着用这样的方法:

SELECT u.id, u.name, u.current_score 
FROM users u 
where u.current_score not in 
(select h.score from histories h where 
h.user_id=u.id order by h.date desc limit 1)

这引发了一个错误:


# 1235 - This version of MariaDB doesn't yet support

'LIMIT & IN/ALL/ANY/SOME subquery'

如果我去掉限制1,那么它将返回用户中几乎所有的行—每个表中有几千行,但我认为它应该返回大约50行,但它在4285个可能的行中返回4100多行

rn0zuynd

rn0zuynd1#

您需要的一种方法是使用子查询来获取 date 与每个 user_id . 在此之后,您可以再次加入表 histories 获取与此最新版本相关联的其他列 date . 这将在下一个查询中进行总结:

SELECT
    u.id,
    u.name,
    u.current_score,
    h.score AS latest_score_from_history
FROM
    user AS u
LEFT JOIN
    -- This subquery gets the date of the latest history register for every user
    (SELECT
         user_id,
         MAX(date) AS maxDate
     FROM
         histories
     GROUP BY
         user_id) AS latest ON latest.user_id = u.id
LEFT JOIN
    histories AS h ON h.user_id = latest.user_id AND h.date = latest.maxDate
WHERE
    u.current_score <> h.score
cig3rfwq

cig3rfwq2#

在相关子查询中,在 Select 条款本身。 Group By 在用户上,使用 HAVING 子句来考虑当前分数与历史上最新分数不匹配的情况
我必须使用 MAX() 对score值的聚合函数,使其符合有效的ansi-sql GROUP BY . 它不会影响任何东西,因为各个分数值只有一个(因此只有最大值)。
请尝试以下操作:

SELECT u.id, 
       u.name, 
       MAX(u.current_score) AS m_current_score, 
       MAX((select h.score 
           from histories h 
           where h.user_id = u.id 
           order by h.date desc limit 1)) AS history_score 
FROM users u 
GROUP BY u.id, u.name 
HAVING m_current_score <> history_score

相关问题