【问题标题】:SQL LEFT-JOIN on 2 fields for MySQLMySQL 的 2 个字段上的 SQL LEFT-JOIN
【发布时间】:2013-09-25 17:16:08
【问题描述】:

我有一个视图A 和一个视图B

A 中,我有很多关于某些系统的信息,例如IPport,我想保留所有这些信息。在B 中,我只想在A 添加一条信息。

两个视图之间的匹配字段是IPPort。所以我必须在两个视图中匹配那些具有相同 IP 和端口的主机。

例子:

查看 A:

IP | OS     | Hostname | Port | Protocol
1  | Win    | hostONE  | 80   | tcp 
1  | Win    | hostONE  | 443  | tcp 
1  | Win    | hostONE  | 8080 | tcp 
2  | Linux  | hostTWO  | 21   | tcp
2  | Linux  | hostTWO  | 80   | tcp
3  | Linux  | hostTR   | 22   | tcp

视图 B:

IP | Port | State
1  | 443  | Open
2  | 80   | Closed

输出

IP | OS     | Hostname | Port | Protocol | State
1  | Win    | hostONE  | 80   | tcp      |
1  | Win    | hostONE  | 443  | tcp      | Open
1  | Win    | hostONE  | 8080 | tcp      |
2  | Linux  | hostTWO  | 21   | tcp      | Closed
2  | Linux  | hostTWO  | 80   | tcp      |
3  | Linux  | hostTR   | 22   | tcp      |

注意:视图A的某些主机可能在视图B中没有IP/Port相关项。

也可能是视图A的某些主机在视图B中有一些匹配。

我认为我应该使用 LEFT JOIN 以获得视图 A 的所有条目和视图 B 的正确关联条目,但它不起作用。 我无法使用正确的 WHERE 子句和 JOIN 解决方案调整查询。

有什么想法吗?

【问题讨论】:

  • 你尝试了什么?向我们展示您的代码示例
  • 您的WHERE 子句包含什么?

标签: mysql sql join left-join


【解决方案1】:
select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

【讨论】:

  • 谢谢!我缺少的是 ON 子句中的双 =!
【解决方案2】:

让我们试试这个方法:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

因此,在where 子句中,您只能通过这种方式从右表中按列过滤结果集:

...
where b.somecolumn <> (=) null

【讨论】:

  • 感谢您的回答以及关于 WHERE 子句的详细信息。
猜你喜欢
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2016-12-14
  • 2015-07-05
  • 1970-01-01
  • 2010-09-29
相关资源
最近更新 更多