【问题标题】:How can I query for rows with latest date and do an inner join on a second table?如何查询具有最新日期的行并在第二个表上进行内部联接?
【发布时间】:2015-04-23 18:27:51
【问题描述】:

我见过的所有示例都展示了如何使用别名进行内部联接以获取具有最新日期的行。我可以用我的数据做到这一点,但我也想在另一个表上做一个内部连接,但不知道如何用同一个查询来做这两个。

这是两张表:

CREATE TABLE `titles` (
  `titleID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `titlename` tinytext NOT NULL,
  `url` varchar(255) DEFAULT '',
  `category` int(2) unsigned NOT NULL,
  `postdate` date NOT NULL,
  PRIMARY KEY (`titleID`),
  KEY `category` (`category`),
  CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`category`) REFERENCES `categories` (`catid`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


CREATE TABLE `stats` (
  `statid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `score` decimal(3,2) DEFAULT NULL,
  `views` int(11) unsigned DEFAULT NULL,
  `favs` int(11) DEFAULT NULL,
  `comments` int(11) DEFAULT NULL,
  `updatedate` date NOT NULL,
  `title` int(11) unsigned NOT NULL,
  PRIMARY KEY (`statid`),
  KEY `title` (`title`),
  CONSTRAINT `stats_ibfk_1` FOREIGN KEY (`title`) REFERENCES `titles` (`titleID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

我的目标:

1) 我想要一个能够为我提供每个标题的所有最新统计信息的查询。

2) 我想查看标题的文本名称(来自标题表)。

我可以使用此查询来获取每个标题的最新分数。

select t.score, t.views, t.favs, t.comments, t.updatedate, t.title
from stats t 
inner join (
select title, max(updatedate) as updatedate 
from stats
GROUP BY title
) tm on t.title = tm.title and t.updatedate = tm.updatedate 

但是这个查询的问题是它显示了来自 stats 的标题列,它是一个 int。我想要标题的文本名称。

我可以这样做来获取标题名称和分数,但是我没有得到最新日期的行。

select titlename, score, updatedate
from stats
inner join titles
on titleid = title

我怎样才能编写一个同时实现我的两个目标的查询?

【问题讨论】:

    标签: mysql sql join


    【解决方案1】:

    在这种情况下,您需要将title 表加入为

    select 
    s1.score, 
    s1.views, 
    s1.favs, 
    s1.comments, 
    s1.updatedate, 
    t.titlename
    from titles t 
    join stats s1 on s1.title = t.titleID
    join (
     select title, max(updatedate) as updatedate 
     from stats
     GROUP BY title
    ) s2 on s2.title = s1.title and s1.updatedate = s2.updatedate 
    

    【讨论】:

    • 非常感谢阿比克!你给了我答案,还有很多需要考虑的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2011-05-07
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 2019-08-10
    • 2021-12-15
    相关资源
    最近更新 更多