简体   繁体   中英

Join multiple query result tables

I have two tables as following:

table #1: graph

在此处输入图片说明

table #2: junctions

在此处输入图片说明

What I want to do is to join both tables into one table. But not with the tables "directly", but rather with query result tables of the tables.

I have 3 query result tables which I want to join:

query result table #1:

SELECT "from", st_x(st_pointn(geom,1)), st_y(st_pointn(geom,1))
FROM public.graph;

在此处输入图片说明

query result table #2:

SELECT "to", st_x(st_pointn(geom,st_npoints(geom))), st_y(st_pointn(geom,st_npoints(geom)))
FROM public.graph;

在此处输入图片说明

query result table #3:

SELECT id, priority
FROM public.junctions;

在此处输入图片说明

As I have written above, those 3 result query tables should now be joined to one table which should look like this:

在此处输入图片说明

Which basically means I want to join the first two result query tables, delete all duplicate entries and then join the third result query table so that every entry has a priority in addition.

How can I achieve this using SQL? Which joins do I need and how is the syntax when joining result table queries? Thanks in advance!

You can try following code, I have used cte to separate each result and in the end I have consolidate them in one query to display desired output. You can modify the JOIN condition or select columns that are required in the output.

WITH CTE_result1 AS
(
SELECT "from", st_x(st_pointn(geom,1)), st_y(st_pointn(geom,1))
FROM public.graph
),
CTE_result2 AS
(
SELECT "to", st_x(st_pointn(geom,st_npoints(geom))), st_y(st_pointn(geom,st_npoints(geom)))
FROM public.graph
),
CTE_result3 AS
(
SELECT id, priority
FROM public.junctions
)
SELECT
        CTE_result1.ID,
        CTE_result1.st_x    AS x,
        CTE_result1.st_y    AS Y,
        priority
FROM
        CTE_result1
    JOIN
        CTE_result2
            ON 'from' = 'To'
    JOIN
        CTE_result3
            ON ID = 'FROM'
               AND ID = 'To';

This query down below does the trick:

Select "from", st_x, st_y, priority from (SELECT "from" , st_x(st_pointn(geom,1)) , 
st_y(st_pointn(geom,1)) 
FROM public.graph
union
SELECT "to", st_x(st_pointn(geom,st_npoints(geom))) , 
st_y(st_pointn(geom,st_npoints(geom))) 
FROM public.graph
order by "from") as nodes  inner join
junctions on nodes."from" = id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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