1

考虑以下查询:

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

AS它看到的第一个查询错误。

即使我更改insertuserid AS transaction_user_id为Unioninsertuserid的第一个,它也会在下一行的第二个错误:!!!SELECTAS(user_price * (-1)) AS amount

错误信息:

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

谢谢

4

1 回答 1

4

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
于 2013-03-16T09:43:57.480 回答