PostgreSQL表合并

时间:2012-11-21 14:40:03

标签: sql postgresql

我有两个数据表,例如:

网络状态

ipaddress       time       violation
192.168.1.1     2:00       yes
192.168.1.6     2:00       no
192.168.1.11    2:00       no
192.168.1.1     3:00       no
192.168.1.6     3:00       no
192.168.1.11    3:00       yes

防火墙日志

ipaddress       machinetype    location
192.168.1.1     computer       London
192.168.1.6     server         New York
192.168.1.11    server         Bejing

我希望将防火墙日志中的数据合并到网络状态表中,以便我有以下内容:

网络状态

ipaddress       time       violation       machinetype       location
192.168.1.1     2:00       yes             computer          London
192.168.1.6     2:00       no              server            New York
192.168.1.11    2:00       no              server            Bejing
192.168.1.1     3:00       no              computer          London
192.168.1.6     3:00       no              server            New York
192.168.1.11    3:00       yes             server            Bejing

有没有人有任何想法?我假设会有一个命令按特定的列值合并表,但是在研究之后我只遇到了连接并选择了命令。但我无法弄清楚如何使用这些来达到我想要的目的。

谢谢!

2 个答案:

答案 0 :(得分:3)

您如何看待视图?将这两个表与一个select组合并从中创建一个视图

CREATE VIEW myView AS SELECT log.*,status.* FROM log, status 
WHERE log.ipaddress=status.ipaddress 

/* OR */
CREATE VIEW myView AS SELECT log.*,status.* FROM log l
INNER JOIN status s ON l.ipaddress=s.ipaddress

答案 1 :(得分:1)

要“合并”这些表,您需要:

1)将“machinetype”和“location”列添加到“Network Status”表:

ALTER TABLE "Network Status"
  ADD COLUMN "machinetype" TEXT;
ALTER TABLE "Network Status"
  ADD COLUMN "location" TEXT;

2)用数据填充它们

UPDATE "Network Status" NS
SET "machinetype" = FL."machinetype",
    "location" = FL."location"
FROM "Firewall Log" FL
WHERE FL."ipaddress" = NS."ipaddress"

或者您可以创建VIEW并将其用于SELECT数据,就好像它是一个表格一样:

CREATE VIEW "Status and log" AS
SELECT NS."ipaddress", NS."time", NS."violation", FL."machinetype", FL."location"
FROM "Network Status" NS
JOIN "Firewall Log" FL ON FL."ipaddress" = NS."ipaddress"