【发布时间】:2021-08-30 09:26:09
【问题描述】:
我有以下两张表:
CREATE DATABASE IF NOT EXISTS springbootdb;
DROP TABLE IF EXISTS occupancy;
DROP TABLE IF EXISTS hotel;
CREATE TABLE hotel
(
id INT NOT NULL PRIMARY KEY auto_increment,
category int NOT NULL,
name TEXT NOT NULL,
owner TEXT NOT NULL,
contact TEXT NOT NULL,
address TEXT NOT NULL,
city TEXT NOT NULL,
zip TEXT NOT NULL,
phone TEXT NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE occupancy
(
id int not null primary key auto_increment,
hotelid int not null,
month int not null,
year int not null,
room_utilization int not null,
bed_utilization int not null,
room_count int not null,
bed_count int not null,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
现在我想显示每个 hotel.id 和 hotel.name 以及 occupancy.room_count、occupancy.bed_count、occupancy.room_utilization 和 occupancy.bed_utilization - 但只有每个 hotel.id 的最新条目,所以那些其中 occupancy.year 和 occupancy.month 分别是最高值。
我尝试了几件事,例如
SELECT springbootdb.hotel.id, springbootdb.hotel.name, springbootdb.occupancy.bed_count, springbootdb.occupancy.bed_utilization
From springbootdb.hotel
INNER JOIN springbootdb.occupancy
ON hotel.id = occupancy.hotelid
order by springbootdb.occupancy.`year`, springbootdb.occupancy.`month` asc limit 1;
但遗憾的是没有取得任何成功。
有好心人能告诉我怎么去吗? 谢谢!
【问题讨论】:
标签: mysql greatest-n-per-group