按查询分组-选择具有最大日期的行

时间:2020-07-02 12:04:10

标签: mysql sql

嗨,我有这个成绩表,并且在前端的报告中,我必须显示关键字和url以及最新扫描的得分。

CREATE TABLE `scores` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `keyword` varchar(200) DEFAULT NULL,
  `url` varchar(200) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  `check_date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

这是我的示例数据:

Sample Data

| id | keyword  | url                  | score | check_date |
|----|----------|----------------------|-------|------------|
| 1  | facebook | https://facebook.com | 10    | 2020-10-21 |
| 2  | facebook | https://facebook.com | 30    | 2020-10-25 |
| 3  | fb       | https://facebook.com | 55    | 2020-10-23 |
| 4  | fb       | https://facebook.com | 20    | 2020-10-24 |

我的查询

SELECT s1.*
FROM scores s1
JOIN scores s2
  ON s1.id = s2.id
WHERE s1.check_date = s2.check_date 
GROUP BY keyword,url

它为特定的关键字url返回正确的check_date,但分数不符合该日期。请帮忙。

1 个答案:

答案 0 :(得分:0)

请勿为此使用聚合。一个简单的方法是相关子查询:

select s.*
from scores s
where s.check_date = (select max(s2.check_date)
                      from scores s2
                      where s2.keyword = s.keyword and s2.url = s.url
                     );

如果您打算使用显式join,则可以使用left join,查找较大的日期,然后返回没有较大日期的行:

select s.*
from scores s left join
     scores slater
     on slater.keyword = s.keyword and
        slater.url = s.url and
        slater.check_date > s.check_date
where slater.check_date is null;
相关问题