所以我有2个这种格式的表,
actual_data:
ID,ROLL_NO,ADM_DT,FEES
1,9895987650,2017-11-14,10000
2,78578686,2017-11-10,130
3,434343,2017-11-15,20
TEMP_DATA:
ID,R_NO,FS,FT
1,9895987650,9000,F1
5,9895987650,5000,F2
3,78578686,150,F3
4,123456,24141,F4
我试图在这里创建一个存储过程,
DELIMITER $$
CREATE PROCEDURE `myproc`()
BEGIN
SELECT a.*,b.* FROM actual_data a, temp_data b
WHERE a.ROLL_NO = b.R_NO
AND
((b.FS >= a.FEES AND b.FT IS NOT NULL)
OR
(b.FS < a.FEES AND b.FT IS NOT NULL));
END $$
DELIMITER;
这将给我以下结果:
ID,ROLL_NO, ADM_DT, FEES,ID, R_NO,FS, FT
1, 9895987650,2017-11-14, 10000, 1, 9895987650,9000, F1
1, 9895987650,2017-11-14, 10000, 5, 9895987650,5000, F2
2, 78578686, 2017-11-10, 130, 3, 78578686,150, F3
现在这就是我被困的地方。
我想做的是,
如果b.FS >= a.FEES AND b.FT IS NOT NULL
为TRUE
,我希望select R_NO,sum(FEES) GROUP BY R_NO HAVING sum(FEES) > 1000 ORDER BY R_NO
来自上述查询结果。
如果b.FS < a.FEES AND b.FT IS NOT NULL
为TRUE
,我希望select R_NO,sum(FEES) GROUP BY R_NO HAVING sum(FEES) < 1000 ORDER BY R_NO
来自上述查询结果。
这可以通过存储过程完成吗?如果是这样,我能否就如何做到这一点得到一些建议?我是MySql的新手,所以请帮助我。
以下是我的努力:
DELIMITER $$
DROP PROCEDURE IF EXISTS `myproc` $$
CREATE PROCEDURE `myproc`()
BEGIN
DECLARE firstCond INT;
DECLARE secondCond INT;
CREATE TEMPORARY TABLE firstTemp
SELECT a.*,b.R_NO,b.FS,b.FT FROM actual_data a, temp_data b
WHERE a.ROLL_NO = b.R_NO AND (b.FS >= a.FEES AND b.FT IS NOT NULL);
CREATE TEMPORARY TABLE secondTemp
SELECT a.*,b.R_NO,b.FS,b.FT FROM actual_data a, temp_data b
WHERE a.ROLL_NO = b.R_NO AND (b.FS < a.FEES AND b.FT IS NOT NULL);
SELECT COUNT(1) INTO firstCond FROM firstTemp;
SELECT COUNT(1) INTO secondCond FROM secondTemp;
IF firstCond > 0 THEN
SELECT f.ID,f.R_NO,SUM(f.FS) AS FS INTO OUTFILE 'C:/Users/MySqlProcFirstOutput1.txt'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
FROM firstTemp f
GROUP BY f.R_NO,f.ID
HAVING SUM(f.FS) > 50
ORDER BY f.R_NO,f.ID ASC;
END IF;
IF secondCond > 0 THEN
SELECT s.ID,s.R_NO,SUM(s.FS) AS FS INTO OUTFILE 'C:/Users/Output2.txt'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
FROM secondTemp s
GROUP BY s.R_NO,s.ID
HAVING SUM(s.FS) > 50
ORDER BY s.R_NO,s.ID ASC;
END IF;
END $$
DELIMITER ;
我想知道的是,这是否是优化的方法?