【问题标题】:Using MySQL join to show unrelated records使用 MySQL join 显示不相关的记录
【发布时间】:2013-06-23 14:58:21
【问题描述】:

我有一个机器表,以及一个表示这些机器跨时间可达性的表。

machines
id    name
1     machine1
2     machine2
3     machine3
4     machine4

machines_reachability
machine_id    is_reachable    time
1             0               (whatever)
2             1               (whatever)
3             0               (whatever)
1             1               (whatever)
2             0               (whatever)
3             0               (whatever)
1             1               (whatever)
2             1               (whatever)
3             1               (whatever)

我正在尝试查找具有NO可达性记录的机器(即 machine4)使用 JOINS。这可以通过其他方式完成,但我需要通过连接来完成,以便更好地理解它。

我尝试了以下

SELECT * FROM machines m LEFT OUTER JOIN machines_reachability mr ON m.id = mr.machine_id

我知道这应该输出整个左表内容(即机器)并且OUTER关键字应该排除基于条件的machinesmachines_reachability表之间的结果交集m.id = mr.machine_id。但这并没有像我预期的那样奏效。它显示了所有内容,但不排除匹配的行。

那么,我如何运行JOIN 查询来实际显示没有加入的行,无论是左表还是右表。

【问题讨论】:

    标签: mysql join outer-join


    【解决方案1】:

    选择不同的machines.names,其中机器自然左外连接machines_rechability,其中is_reachable为空

    【讨论】:

    • 如果我省略了where is_reachable is null,我将找不到is_reachable 的值为null 的行。那么这个条件首先是如何工作的呢?!
    • 如果您删除 is_reachable 为空条件,那么您将收到一个带有 Machine1 Machine2 Machine3 Machine4 的表
    【解决方案2】:

    使用连接:

    select *
    from machines m left outer join
         machines_reachability mr
         on m.id = mr.machine_id and
            mr.is_reachable = 1
    where mr.machine_id is NULL
    

    这个想法是从所有机器开始。 left join 将所有记录保留在第一个表中,即使是那些不匹配的记录。当机器可达时,第二个表中有一个匹配项(我假设记录必须设置标志并且在表中)。最后的where 子句只保留第二个表中没有匹配的机器。

    【讨论】:

    • 一件事让我很困惑,如果我不按mr.machine_id IS NULL 过滤,我会从machines 表中获取所有行,但不会从machines_reachability 表中获取所有行,machine_id 等于@ 987654328@。那么为什么WHERE mr.machine_id IS NULL 首先工作?!
    • 啊,我明白了。谢谢。
    • 你和John smith 回答了一个正确的答案,但他早了几分钟,我不得不接受他的回答才能公平。非常感谢您抽出宝贵的时间 :)
    【解决方案3】:

    怎么样

    SELECT * from machines where not exists 
    ( 
          select machine_id from machines_reachability 
          where machines.id = machines_reachability.machine_id 
    );
    

    【讨论】:

    • 我需要使用JOIN
    • 我实际上是在学习JOINS,而不是试图产生结果。
    【解决方案4】:
    SELECT *
    FROM machines m
    JOIN machines_reachability mr
      ON (m.id <> mr.machine_id)
    GROUP BY m.id;
    

    【讨论】:

    • 我正在尝试查找在machines_reachability 表中没有任何信息的machines
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2012-08-08
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多