2

我在 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 左右,但它在 4,285 个可能的行中返回超过 4,100 行

4

2 回答 2

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
于 2018-11-13T21:02:56.030 回答
0

您需要的一种方法是使用子查询来获取date与每个user_id. 在此之后,您可以再次加入该表histories以获取与该 latest 关联的其余列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
于 2018-11-13T21:42:22.187 回答