【问题标题】:How to join without duplicates and on a max date? [duplicate]如何在没有重复的情况下加入并在最大日期内加入? [复制]
【发布时间】:2021-04-28 06:35:13
【问题描述】:

我有一张酒店桌子和一张访问酒店的访问桌子。如何在不多次显示同一家酒店的情况下加入表格并显示最后一次访问的日期,条件是最后一次访问是在2021-01-01 9:00:00之后

我想要什么:

+------+---------------------+
| name |    last_visited     |
+------+---------------------+
| red  | 2021-01-01 09:34:00 |
| blue | 2021-01-01 10:04:00 |
+------+---------------------+

create table hotels (
  id int auto_increment primary key,
  name varchar(32)
);

create table visits (
  hotel int not null, FOREIGN KEY (hotel) REFERENCES hotels (id),
  customer varchar(32) not null,
  date_visited datetime not null
);

INSERT INTO hotels (name) values ('red'), ('blue'), ('green');
INSERT INTO visits (hotel, customer, date_visited) values
(1, 'bob', '2021-01-01 09:00:00'),
(1, 'james', '2021-01-01 09:05:00'),
(1, 'billy', '2021-01-01 09:34:00'), 
(2, 'sarah', '2021-01-01 09:34:00'), 
(2, 'heather', '2021-01-01 10:04:00'), 
(3, 'glenn', '2021-01-01 07:32:00'),
(3, 'jonah', '2021-01-01 08:41:00'), 
(3, 'amy', '2021-01-01 8:59:00');

我的尝试

select h.name, v.date_visited as last_visited
from hotels h
left join visits v
on h.id = v.hotel
WHERE v.date_visited > '2021-01-01 9:00:00';

【问题讨论】:

  • select max(v.date_visited) ... group by h.name??

标签: mysql sql database join select


【解决方案1】:

使用聚合函数 max()

select h.name, max(v.date_visited )as last_visited
from hotels h
join visits v
on h.id = v.hotel
WHERE v.date_visited > '2021-01-01 9:00:00'
group by h.name

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2018-03-10
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多