MYSQL选择同时在同一家酒店的员工夫妻

标签 mysql sql

嘿,我正在努力处理 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/

相关文章:

mysql - 为什么 MySQL 不使用我的分区作为索引?

mysql - WHERE EXISTS 不起作用

php - 计算数据表/数据库中某些输入的出现次数

PHP MySQL - URL 结构

php - 将日期与存储在其他列中的持续时间进行比较的 postgresql 查询

mysql - 如果表只包含外键,表可以自动填充吗?

php - MySQL 和 PHP 中的多行合并为一行

mysql - COUNT 多表查询,我必须在其中显示 COUNT 个结果

php和mysql多维值

mysql - 使用 LEFT 连接连接值