i have the this MYSQL SP that does SUm against different tables but i wanted the SP to return all the results in one table one row i tried using + to combine results from the selects but it gets error
DROP PROCEDURE IF EXISTS x.GetFinanceContent;
delimiter //
CREATE PROCEDURE x.GetFinanceContent
(
IN userId INT
)
BEGIN
(SELECT SUM开发者_StackOverflow中文版(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;//
Error Code: 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 '+ (SELECT SUM(AMOUNT) AS debitTotal FROM x.Card WHERE user_Id ' at line 10 0.000 sec
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
)
If you want to SUM those sums you can make query like this:
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
Use union http://dev.mysql.com/doc/refman/5.0/en/union.html If you want to get one result set....
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;//
Although I am rusty now with SQL and too lazy to check if syntax is correct, I think it should work.
精彩评论