当我在mysql存储过程下运行时,我得到三个不同的表作为输出。有没有办法,我可以将这三个表和显示输出组合在一个具有不同列和单行的表中吗?
CREATE DEFINER=`root`@`localhost` PROCEDURE `retrieveApplicantStatus`(IN in_userId INT)
BEGIN
SELECT applicants_id, approval FROM applicants WHERE users_id = in_userId;
SELECT pass_fail.result AS test_result, pass_fail.license_approval FROM pass_fail WHERE user_id = in_userId;
SELECT result AS trial_result FROM trial_result WHERE user_id = in_userId;
END
必需输出:
--------------------------------------------------------------------------
applicants_id | approval | test_result | trial_result | license_approval |
--------------------------------------------------------------------------
| | | | |
--------------------------------------------------------------------------
答案 0 :(得分:1)
如果user_id
在每个表格中被限制为唯一,那么您可以使用:
CREATE DEFINER=`root`@`localhost` PROCEDURE `retrieveApplicantStatus`(IN in_userId INT)
BEGIN
SELECT u.in_userId,
a.applicants_id,
a.approval,
pf.result AS test_result,
pf.license_approval,
tr.result AS trial_result
FROM (SELECT in_userId) AS u
LEFT JOIN applicants AS a
ON a.users_id = u.in_userId
LEFT JOIN pass_fail AS pf
ON pf.user_id = u.in_userId
LEFT JOIN trial_result AS tr
ON tr.user_id = u.in_userId;
END
HOWEVER 如果它不被限制为唯一,那么这将给你一个笛卡尔积,即每个表中的2行总共会给你8行,每个表中的3行会给你27行结果。
答案 1 :(得分:-1)
尝试使用以下代码: -
BEGIN
SELECT applicants_id, approval
FROM applicants WHERE users_id = in_userId;
UNIION ALL
SELECT pass_fail.result AS test_result, pass_fail.license_approval
FROM pass_fail
WHERE user_id = in_userId;
UNION ALL
SELECT result AS trial_result
FROM trial_result
WHERE user_id = in_userId;
END