简体   繁体   English

`SELECT field AS`在2个表之间使用UNION会导致错误#1064

[英]`SELECT field AS` to use UNION between 2 tables causes error#1064

Consider the following query: 请考虑以下查询:

SELECT x.* FROM
(
    (
        SELECT (id,
            insertuserid AS transaction_user_id,
            (user_price * (-1)) AS amount,
            "INVOICE" AS transaction_type,
            insertdatetime
            )
        FROM invoice
        WHERE transaction_user_id = 4
    )
    UNION
    (
        SELECT (id,
            user_id AS transaction_user_id,
            amount,
            "PAYMENT" AS transaction_type,
            insertdatetime)
        FROM payment
        WHERE user_id = 4
    )
)
AS x
ORDER BY x.insertdatetime

The query errors on the first AS it sees. 它看到的第一个AS上的查询错误。

Even when I change insertuserid AS transaction_user_id to insertuserid in the first SELECT of Union, it errors on the second AS that is at the next line: (user_price * (-1)) AS amount !!! 甚至当我改变insertuserid AS transaction_user_idinsertuserid第一SELECT联盟,它的第二个错误AS也就是下一行: (user_price * (-1)) AS amount

Error message: 错误信息:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
'AS transaction_user_id, (user_price * (-1)) AS amount, "' at line 5


SELECT x.* FROM ( ( SELECT (id, insertuserid AS transaction_user_id,
(user_price * (-1)) AS amount, "INVOICE" AS transaction_type, insertdatetime )
FROM invoice WHERE transaction_user_id = 4 ) UNION
( SELECT (id, user_id AS transaction_user_id, amount,
"PAYMENT" AS transaction_type, insertdatetime) FROM payment
WHERE user_id = 4 ) ) AS x
ORDER BY x.insertdatetime

Thank you 谢谢

just remove the parenthesis on the SELECT clause, 只需删除SELECT子句中的括号,

SELECT  x.* 
FROM
    (
        SELECT  id,
                insertuserid AS transaction_user_id,
                user_price * (-1) AS amount,
                'INVOICE' AS transaction_type,
                insertdatetime
        FROM    invoice
        WHERE   transaction_user_id = 4
        UNION
        SELECT  id,
                user_id AS transaction_user_id,
                amount,
                'PAYMENT' AS transaction_type,
                insertdatetime
        FROM    payment
        WHERE   user_id = 4
    ) AS x
ORDER BY x.insertdatetime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM