0

我需要从 postgresql 数据库中提取一些数据,从两个 tobles 中的每一个中提取一些元素。这些表包含与物理网络设备相关的数据,其中一个表专门用于这些设备的 MAC 地址。每个设备都由位置(车辆)和功能(dev_name)标识。

表1(资产):

vehicle
dev_name
dev_serial
dev_model

表2:(mac)

vehicle
dev_name
mac
interface

我尝试了什么:

SELECT assets.vehicle, assets.dev_name, dev_model, dev_serial, mac
    FROM assets, macs
    AND interface = 'E0'
    ORDER BY vehicle, dev_name
;

但它似乎不像我想象的那样匹配车辆和 dev_name。相反,它似乎打印了 mac 和 dev_serial 的每个组合,这不是预期的输出,因为我想要每个组合一行。

如何根据 assets.dev_name = macs.dev_name 和 assets.vehicle = macs.vehicle 确保它的 mac 地址与设备匹配?

注意: 中的某些设备assets可能没有记录的 mac 地址mac,在这种情况下,我希望它们以空的 mac 显示

4

3 回答 3

3

使用时,join您可以指定哪些列必须匹配

SELECT a.vehicle, a.dev_name, dev_model, dev_serial, mac
FROM assets a
LEFT JOIN macs m ON m.vehicle = a.vehicle 
                 AND m.dev_name = a.dev_name
WHERE interface = 'E0'
ORDER BY a.vehicle, a.dev_name
于 2013-09-03T10:13:13.090 回答
0

A simple join keyword is the solution of your problems

SELECT assets.vehicle, assets.dev_name, dev_model, dev_serial, mac
FROM assets A join macs M
ON A.dev_name = M.dev_name

Otherwise going on with your approach, just modify the query as follows:

SELECT assets.vehicle, assets.dev_name, dev_model, dev_serial, mac
FROM assets, macs
WHERE interface = 'E0' AND assets.dev_name = macs.dev_name
ORDER BY vehicle, dev_name;

remember that for any join the condition is very important, other wise it just becomes another cross join, i.e. combination of each row with every other row.

于 2013-09-03T11:33:06.287 回答
0

阅读有关SQL 连接的信息。

select
   a.vehicle, a.dev_name, a.dev_model, a.dev_serial, m.mac
from assets as a
    inner join macs as m on m.dev_name = a.dev_name and m.vehicle = a.dev_name 
where m.interface = 'E0'
order by a.vehicle, a.dev_name

在您的情况下,它是内连接,但如果您想获取所有资产并为具有接口 E0 的资产显示 mac,您可以使用左外连接

select
   a.vehicle, a.dev_name, a.dev_model, a.dev_serial, m.mac
from assets as a
    left outer join macs as m on
        m.dev_name = a.dev_name and m.vehicle = a.dev_name and m.interface = 'E0'
order by a.vehicle, a.dev_name
于 2013-09-03T10:22:06.467 回答