如何修复“缺少表的 FROM 子句条目”?

Posted

技术标签:

【中文标题】如何修复“缺少表的 FROM 子句条目”?【英文标题】:How to fix 'missing FROM-clause entry for table'? 【发布时间】:2019-01-15 21:32:42 【问题描述】:

我有一个查询功能。如果条件为真,我用新值更新一行。

我做一个查询:

SELECT * FROM transfer_flight(41313, '2017-08-15 20:00:00+05');

我得到一个错误:

错误:表“航班”缺少 FROM 子句条目 第 1 行:选择 (flights.scheduled_departure zone) line 7 at IF

CREATE OR REPLACE FUNCTION flightFunc(
    flight_identificator INTEGER, 
    new_timestamp timestamp with time zone) 
RETURNS TABLE(
    flight_id INTEGER,
    flight_no CHARACTER(6),
    departure_airport character(3),
    scheduled_departure timestamp with time zone,
    arrival_airport character(3),
    scheduled_arrival timestamp with time zone
)
LANGUAGE plpgsql
AS $$
DECLARE 
    flight_d timestamp with time zone =  scheduled_arrival - 
scheduled_departure;

BEGIN

    IF (flights.scheduled_departure < $2)
    THEN
        UPDATE flights
            scheduled_departure = $2,
            scheduled_arrival = $2 + flight_d
        FROM flights
        WHERE flights.flight_id = $1
        RETURNING 
            flights.flight_id,  
            flights.flight_no,
            flights.departure_airport,
            flights.scheduled_departure,
            flights.arrival_airport,        
            flights.scheduled_arrival;
    END IF;

END;
$$;

结果我应该只需要使用输入 flight_identificator 更新一行

【问题讨论】:

【参考方案1】:

删除FROM 子句!那就是CROSS JOIN。你需要SET。所以:

UPDATE flights
    SET scheduled_departure = $2,
        scheduled_arrival = $2 + flight_d
    WHERE flights.flight_id = $1
RETURNING 
    flights.flight_id,  
    flights.flight_no,
    flights.departure_airport,
    flights.scheduled_departure,
    flights.arrival_airport,        
    flights.scheduled_arrival;

【讨论】:

我创建了一个函数。但是当我在查询中调用函数时: SELECT * FROM transfer_flight(41313, '2017-08-15 20:00:00+05');我从这个问题的主题中得到错误【参考方案2】:

在我看来,您应该摆脱 flight_d 变量和 IF 块,并将逻辑移至查询本身,例如:

CREATE OR REPLACE FUNCTION flightFunc(
    flight_identificator INTEGER, 
    new_timestamp timestamp with time zone) 
RETURNS TABLE(
    flight_id INTEGER,
    flight_no CHARACTER(6),
    departure_airport character(3),
    scheduled_departure timestamp with time zone,
    arrival_airport character(3),
    scheduled_arrival timestamp with time zone
)
LANGUAGE plpgsql
AS $$

BEGIN

    UPDATE flights SET
        scheduled_departure = $2,
        scheduled_arrival = $2 + flights.scheduled_arrival - flights.scheduled_departure
    WHERE flights.flight_id = $1 AND flights.scheduled_departure < $2
    RETURNING 
        flights.flight_id,  
        flights.flight_no,
        flights.departure_airport,
        flights.scheduled_departure,
        flights.arrival_airport,        
        flights.scheduled_arrival;

END;
$$;

【讨论】:

以上是关于如何修复“缺少表的 FROM 子句条目”?的主要内容,如果未能解决你的问题,请参考以下文章

查询中的错误 - 缺少表的 FROM 子句条目 - SQL

Rails PG::UndefinedTable: 错误: 缺少表的 FROM 子句条目

返回导致错误:缺少表的 FROM 子句条目

如何修复“缺少'使用严格'声明”?

如何修复 Typescript 中的“以下属性中缺少类型''...”错误?

如何让 VScode 自动修复缺少的分号 Apex?