Синтаксическая ошибка Postresql на или рядом с ‘FROM’ в подзапросе

#sql #postgresql #subquery

#sql #postgresql #подзапрос

Вопрос:

Я пытаюсь выполнить подзапрос psql, как показано ниже:

 SELECT invoices.*, contractors.name AS contractor
FROM (SELECT id AS resource_id,
    'OutgoingInvoice' AS resource_type,
    creation_date AS date,
    number AS description,
    total_gross_amount_cents,
    total_discount_amount_cents,
    'false' AS credit_note,
    created_at
FROM outgoing_invoices
WHERE customer_id = 1
AND payment_status = 'unpaid'
AND cancelled_outgoing_invoice_id IS NULL
AND draft = 'false') invoices
FROM outgoing_invoices
WHERE customer_id = 1
AND payment_status = 'unpaid'
AND cancelled_outgoing_invoice_id IS NULL
AND draft = 'false'
  

И застрял здесь:

 ERROR:  syntax error at or near "FROM"
LINE 15: FROM outgoing_invoices
  

Чего мне не хватает?

Комментарии:

1. у вас не может быть двух FROM предложений

Ответ №1:

У вас есть дубликат ИЗ предложений outgoing_invoices. Может быть полезно сделать отступ в запросе, чтобы сделать его более понятным:

 SELECT
    invoices.*,
    contractors.name AS contractor
FROM (
        SELECT
            id AS resource_id,
            'OutgoingInvoice' AS resource_type,
            creation_date AS date,
            number AS description,
            total_gross_amount_cents,
            total_discount_amount_cents,
            'false' AS credit_note,
            created_at
        FROM outgoing_invoices
        WHERE customer_id = 1
            AND payment_status = 'unpaid'
            AND cancelled_outgoing_invoice_id IS NULL
            AND draft = 'false'
    ) invoices
FROM outgoing_invoices
WHERE customer_id = 1
AND payment_status = 'unpaid'
AND cancelled_outgoing_invoice_id IS NULL
AND draft = 'false'
  

Итак, в вашем случае это должно быть что-то вроде

 SELECT
        invoices.*,
        contractors.name AS contractor
    FROM (
            SELECT
                id AS resource_id,
                'OutgoingInvoice' AS resource_type,
                creation_date AS date,
                number AS description,
                total_gross_amount_cents,
                total_discount_amount_cents,
                'false' AS credit_note,
                created_at
            FROM outgoing_invoices
            WHERE customer_id = 1
                AND payment_status = 'unpaid'
                AND cancelled_outgoing_invoice_id IS NULL
                AND draft = 'false'
        ) invoices