我有这个MYSQL SP对不同的表执行SUm但是我希望SP在一个表中返回所有结果我尝试使用+来组合选择的结果但是它得到错误
DROP PROCEDURE IF EXISTS x.GetFinanceContent;
delimiter //
CREATE PROCEDURE x.GetFinanceContent
(
IN userId INT
)
BEGIN
(SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1)
+
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)
END;//
错误代码:1064您输入了错误 你的SQL语法;检查手册 对应于您的MySQL服务器 用于正确语法的版本 靠近'+(SELECT SUM(AMOUNT)AS debitTotal 来自x.Card 用户名_Id'在第10行0.000秒
答案 0 :(得分:2)
SELECT
( SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId AND card_type=1
)
, ( SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId AND card_type=2
)
答案 1 :(得分:0)
如果你想要求和这些总和,你可以这样查询:
SELECT ((SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1) +
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)) as total
使用union http://dev.mysql.com/doc/refman/5.0/en/union.html如果您想获得一个结果集....
DROP PROCEDURE IF EXISTS x.GetFinanceContent;
delimiter //
CREATE PROCEDURE x.GetFinanceContent
(
IN userId INT
)
BEGIN
(SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1)
UNION
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)
END;//
虽然我现在厌倦了SQL并且懒得检查语法是否正确,但我认为它应该可行。