我不知道这个查询有什么问题,在多次尝试后我无法运行。请指出这有什么问题我该如何解决。谢谢。
SELECT
cd.dr
FROM
(
(SELECT SUM(cc.credit_amount) AS cr FROM cust_credit cc) cc
UNION
(SELECT SUM(cd.debit_amount) AS dr FROM cust_debit cd ) cd
)
错误是。
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'cd ) LIMIT 0, 25' at line 7
最佳答案
您不能为 UNION
中的子查询指定别名,也不能使用别名引用子查询的结果。并且 UNION
中的列别名总是来自第一个子查询中的别名,因此您不能引用 dr
。
你可以做的是:
SELECT amount
FROM (
SELECT 'cc' AS type, SUM(credit_amount) as amount FROM cust_credit
UNION ALL
SELECT 'cd' AS type, SUM(debit_amount) AS amount FROM cust_debit
) x
WHERE type = 'cd'
或者不使用 UNION
,您可以将查询放在 SELECT
列表中。
SELECT dr AS amount
FROM (
SELECT (SELECT SUM(credit_amount) FROM cust_credit) AS cr,
(SELECT SUM(debit_amount) FROM cust_debit) AS dr
) x
关于mysql - 执行前子查询基本错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48433329/