我想爲一些gtfs-feed數據添加一個非規範化表。爲此,我創建了一個新表格:Postgresql錯誤地插入值
CREATE TABLE denormalized_trips (
stops_coords json NOT NULL,
stops_object json NOT NULL,
agency_key text NOT NULL,
trip_id text NOT NULL,
route_id text NOT NULL,
service_id text NOT NULL,
shape_id text,
route_color text,
route_long_name text,
route_desc text,
direction_id text
);
CREATE INDEX denormalized_trips_index ON denormalized_trips (agency_key, trip_id);
CREATE UNIQUE INDEX denormalized_trips_index ON denormalized_trips (agency_key, route_id);
現在我想通過insert語句將數據從一個表傳輸到另一個表。聲明相當複雜。
INSERT INTO denormalized_trips
SELECT
trps.stops_coords,
trps.stops_object,
trps.trip_id,
trps.service_id,
trps.route_id,
trps.direction_id,
trps.agency_key,
trps.shape_id,
trps.route_color,
trps.route_long_name,
trps.route_desc
FROM (
SELECT
array_to_json(ARRAY_AGG(array[stop_lat, stop_lon])) AS stops_coords,
array_to_json(ARRAY_AGG(array[
stops.stop_id,
CAST (stop_times.stop_sequence AS TEXT),
stops.stop_name,
stop_times.departure_time,
CAST (stop_times.departure_time_seconds AS TEXT),
stop_times.arrival_time,
CAST (stop_times.arrival_time_seconds AS TEXT)
])) AS stops_object,
trips.trip_id,
trips.service_id,
trips.direction_id,
trips.agency_key,
trips.shape_id,
routes.route_id,
routes.route_color,
routes.route_long_name,
routes.route_desc
FROM gtfs_stop_times AS stop_times
INNER JOIN gtfs_trips AS trips
ON trips.trip_id = stop_times.trip_id AND trips.agency_key = stop_times.agency_key
INNER JOIN gtfs_routes AS routes ON trips.agency_key = routes.agency_key AND routes.route_id = trips.route_id
INNER JOIN gtfs_stops AS stops
ON stops.stop_id = stop_times.stop_id
AND stops.agency_key = stop_times.agency_key
AND NOT EXISTS (
SELECT 0
FROM denormalized_max_stop_sequence AS max
WHERE max.agency_key = stop_times.agency_key
AND max.trip_id = stop_times.trip_id
AND max.trip_max = stop_times.stop_sequence
)
GROUP BY
trips.trip_id,
trips.service_id,
trips.direction_id,
trips.agency_key,
trips.shape_id,
routes.route_id,
routes.route_color,
routes.route_long_name,
routes.route_desc
) as trps
如果我只是運行內部select語句,我會得到正確的結果。他們看起來是這樣的:(截圖沒有顯示所有的表,因爲它太長)
但如果我執行INSERT語句,並顯示錶的內容,我會得到這樣的:
正如您可能注意到內容未插入到表格的右列中。 agency_key現在具有trip_id的值,並且direction_id現在是service_id(並且有更多的表被混淆)。
所以我的問題是我做錯了,我的插入語句插入內容到新創建表的錯誤列?
感謝您的幫助。
多數民衆贊成它!我將我的選擇語句重新排序,現在它可以工作。這讓我非常頭疼。感謝你的回答 –