在postgis上查询多个表

时间:2012-02-02 05:59:33

标签: sql postgresql postgis mapserver

在postgis中,我有几个表具有相同的结构,但分别代表Mapserver的不同层(1,2,3 ......),

table1
       gid | name     | address       | post code  | layer |  geom
-----------+----------+---------------+------------+-------+------------
        1    'name11'     'address11'   102356       1       geom11
        2    'name12'     'address12'   102356       1       geom12
        -    'name1-'     'address1-'   102356       1       geom1-

table2
       gid | name     | address       | post code  | layer |  geom
-----------+----------+---------------+------------+-------+------------
        1    'name21'     'address21'   102356       2       geom21
        2    'name22'     'address22'   102356       2       geom22
        -    'name2-'     'address2-'   102356       2       geom2-


table3
       gid | name     | address       | post code  | layer |  geom
-----------+----------+---------------+------------+-------+------------
        1    'name31'     'address31'   102356       3       geom31
        2    'name32'     'address32'   102356       3       geom32
        -    'name3-'     'address3-'   102356       3       geom3-

我想从table1,2,3获取查询结果...如果关键字匹配,请说出名称如'name',如下所示:

输入'name',结果就像

results
       gid | name     | address       | post code  | layer |  geom
-----------+----------+---------------+------------+-------+------------
        1    'name11'     'address11'   102356       1       geom11
        2    'name12'     'address12'   102356       1       geom12
        3    'name21'     'address21'   102356       2       geom21
        4    'name22'     'address22'   102356       2       geom22
        5    'name31'     'address31'   102356       3       geom31
        6    'name32'     'address32'   102356       3       geom32
        -      '-'          '-'          -----       -        --

我只需要gid从1开始重新编号,从而获取原始的gid值似乎没有必要:)

我可以用一个查询句子来实现这个结果吗?如何? 任何好的想法都会被批评?

谢谢

1 个答案:

答案 0 :(得分:3)

尝试使用UNION ALLrow_number函数,例如此查询:

SELECT 
row_number() over (ORDER BY a.gid, a.layer) AS qid, 
a.name, a.address, a."post code", a.layer, a.geom
FROM
(
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3
)a
WHERE a.name like 'name%'