繁体   English   中英

用于MySQL的2个字段的SQL LEFT-JOIN

[英]SQL LEFT-JOIN on 2 fields for MySQL

我有一个视图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

OUTPUT

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 /端口相关的项目。

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

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

任何想法?

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

我们这样试试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM