高级连接三表Postgresql

问题描述 投票:0回答:1

我有三个表,其中一个包含存储和使用位置之间的运输移动,它有一个“从”和“到”uuid,以及一个“金额”列。 “from”和“to”列中的 UUID 引用两个表(“storage_location”表或“usage_location”表)之一中的行。现在我不知道 UUID 会在这两个表中的哪一个中找到

现在我正在尝试将移动表传输到“storage_location”表或“usage_location”表,以便我可以将名称和坐标列与传输移动相匹配。结果如下: amount、to_name、to_coordinates、from_name、from_coordinates

一个主要问题是“to”和“from”信息可以位于相同的“usage_location”或“storage_location”表中,但仍然需要根据是否与“to”或“匹配”来更改列名从“uuid”到“to_name”或“from_name”

有人对有条件地命名这些有任何建议吗?或者是否有更好的方法来做到这一点?

表格看起来像:

CREATE TABLE transport (
    amount double precision NOT NULL,
    timestamp_start timestamp without time zone,
    timestamp_end timestamp without time zone,
    "to" uuid,
    "from" uuid,
    type_water character varying
);

CREATE TABLE location_storage (
    type character varying NOT NULL,
    uuid uuid NOT NULL,
    coordinates double precision[],
    status character varying,
    name character varying NOT NULL,
    content_latest double precision,
);

CREATE TABLE location_usage (
    name character varying NOT NULL,
    type character varying,
    coordinates double precision[],
    uuid uuid,
    description text,
    status character varying
);

期望的结果是:

传输表:to (uuid)、amount、to_name(来自使用位置表或存储位置表)、to_coordinates:(来自使用位置表或存储位置表)from (uuid)、from_name(来自使用位置表或存储位置表),to_coordinates:(来自使用位置表或存储位置表)

我尝试过以下方法:

SELECT amount,distance,timestamp_start,type_water,
location_storage.name as to_name, location_storage.type as to_type, location_storage.coordinates as to_coordinates, location_storage.description as to_description, location_storage.status as to_status,
location_usage.name as from_name, location_usage.type as from_type, location_usage.coordinates as from_coordinates,  location_usage.status as from_status
FROM transport
INNER JOIN location_storage ON transport.to = location_storage .uuid OR transport.from = location_storage .uuid
LEFT OUTER JOIN location_usage ON transport.to = location_usage.uuid OR transport.from = location_usage.uuid

但是如果传输“from”和“to”uuid 都位于同一个位置表中,则此方法不起作用

sql postgresql join
1个回答
0
投票

联合位置,然后将

transport
加入该联合两次。

尝试这样的事情:

with locations as (
  select uuid, coordinates, name, 'storage' as location_type
    from location_storage
  union all
  select uuid, coordinates, name, 'usage' as location_type
    from location_usage
)
select dst.uuid as to_uuid, t.amount, dst.name as to_name, 
       dst.coordinates as to_coordinates, src.uuid as from_uuid,
       src.name as from_name, src.coordinates as from_coordinates
  from transport t
       join locations src on src.uuid = t."from"
       join locations dst on dst.uuid = t."to";
© www.soinside.com 2019 - 2024. All rights reserved.