【问题标题】:Compare scores in two tables and show those where the most recent is different比较两个表格中的分数,并显示最近的不同之处
【发布时间】:2019-04-16 18:44:26
【问题描述】:

我在 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

在上面我想显示 Bob,因为他的最新历史与他当前的得分不同,但不显示 Tom,因为他是匹配的

我尝试使用类似的东西:

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 行,但它会返回 4,285 行中的 4,100 多行

【问题讨论】:

    标签: mysql mariadb groupwise-maximum


    【解决方案1】:
    • Select 子句本身内确定相关子查询中的最新历史分数。
    • Group By 在用户上,并使用HAVING 子句来考虑当前分数与历史中最新分数不匹配的情况
    • 我必须对分数值使用MAX() 聚合函数,以便它是符合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
    

    【讨论】:

    • 谢谢 - 我收到一个 SQL 错误:1064 - 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 4 行的“从历史记录 h 中选择 h.score 其中 h.user_id”附近使用正确的语法
    • @bhttoan 添加了一对括号。请检查更新的答案并告诉我
    • 是的,现在似乎已经排序了!
    【解决方案2】:

    您需要的一种方法是使用子查询来获取与每个user_id 的最新历史条目相关的date。在此之后,您可以再次加入表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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2023-03-06
      相关资源
      最近更新 更多