Question

In postgis, I have a couple of tables with same structure but standing for different layers(1,2,3...) respectively for Mapserver,

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-

I want to get query results from table1, 2, 3... if key word matches, say name like 'name' as follows:

input 'name', results will be like

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
        -      '-'          '-'          -----       -        --

I just need gid in increasing order renumbering from 1, fetching their original gid value seems not necessary:)

can I achieve that results with one single query sentence? and how? any good ideas will be appricated?

thanks

Was it helpful?

Solution

Try to use UNION ALL and the row_number function like this query:

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%'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top