嘿,我正在努力处理 mysql 查询。
我必须从同一家酒店且抵达日期相同的成对员工中选择 PNr、HName、arrivalDate
。这些对应按升序排序。
有什么想法吗?我对复杂的 mysql 查询不熟悉,无法弄清楚。
表员工
| #PNr | Name | ANr | Gehalt |
| 1 | Herald | 4 | 28000 |
| 2 | Gudru | 4 | 28000 |
| 3 | Tim | 1 | 32000 |
| 4 | Fred | 1 | 32000 |
| 5 | Frieda | 2 | 27500 |
餐 table 酒店
| #HNr | HName | Kategorie| PLZ | Ort
| 1 | A | 4 | 1234 | Memphis
| 2 | B | 4 | 1234 | New York
| 3 | C | 1 | 1234 | Berlin
| 4 | D | 1 | 1234 | LA
table 行程
| #*employee| #*Hotel | #arrivalDate | Duration | Costs
| 1 | 1 | 12.11.2020 | 7 | 1200
| 1 | 4 | 31.10.2019 | 14 | 2800
| 3 | 4 | 31.10.2019 | 14 | 2800
| 5 | 3 | 09.09.2019 | 3 | 1750
#为主键,*为外键
最佳答案
您可以使用exists
进行过滤:
select
e.pnr,
h.name,
t.arrivalDate
from employees e
inner join travel t
on t.employee = e.pnr
and exists (
select 1
from travel t1
where
t1.hotel = t.hotel
and t1.arrivalDate = t.arrivalDate
and t1.employee <> t.employee
)
inner join hotel h
on h.hnr = t.hotel
或者,在 MySQL 8.0 中,您可以在子查询中进行窗口计数,然后在外部查询中进行过滤:
select prn, name, arrivalDate
from (
select
e.pnr,
h.name,
t.arrivalDate,
count(*) over(partition by h.hnr, t.arrivalDate) cnt
from employees e
inner join travel t on t.employee = e.pnr
inner join hotel h on h.hnr = t.hotel
)
where cnt > 1
关于MYSQL选择同时在同一家酒店的员工夫妻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617092/