嘿,我正在努力处理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 |
餐桌酒店
| #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
餐桌旅行
| #*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
# is primary Key, * is foreign key
您可以使用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
尝试这个简单的方法。
选择e.pnr,h.name,t.arrivalDate来自员工e内部员工旅行t.employee = e.pnr内部加入酒店h on h.hnr = t.hotelh.arrivalDate在(选择t.arrivalDate来自员工e内部员工旅行t.employee = e.pnr内部加入酒店h on h.hnr = t.hotel按t.arrivalDate分组计数(*)> 1)