I have two tables as following:
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:
SELECT "from", st_x(st_pointn(geom,1)), st_y(st_pointn(geom,1))
FROM public.graph;
SELECT "to", st_x(st_pointn(geom,st_npoints(geom))), st_y(st_pointn(geom,st_npoints(geom)))
FROM public.graph;
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.