Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Using the result of a Stored Procedure in an Inner Join

I have a MySQL Stored Procedure that returns multiple rows. Is there a way to use this result in an Inner Join with another table? I've tried:

SELECT ErrorMessage FROM ErrorMessage em 
INNER JOIN User_Language(pCompanyID, pUserID) l ON em.Language=l.LanguageID 
WHERE ErrorCode = pErrorCode 
ORDER BY l.LanguageOrder LIMIT 1;

In this example, User_Language is the stored procedure that returns a list of languages in order of preference. The intent is to return an error message in the user's preferred language.

like image 219
Frank Schnabel Avatar asked May 31 '15 15:05

Frank Schnabel


People also ask

Can we use stored procedure in join?

You can't join on stored procedures. You have to join on tables / result sets. If this is not an option, push the results of the stored procedures to temp tables and then do the join on the temp tables. Use Joins for tables not for stored procedure.

How does inner join work in MySQL?

What is INNER JOIN in MySQL? In MySQL the INNER JOIN selects all rows from both participating tables to appear in the result if and only if both tables meet the conditions specified in the ON clause. JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents. In standard SQL, they are not equivalent.

Can you inner join after WHERE clause?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas.


1 Answers

I found a viable solution. Within the User_Language stored proc, I create a Temp table (called UserLanguages) which I can then use in the inner join.

CALL User_Language(pCompanyID, pUserID);
SELECT ErrorMessage INTO vErrorMessage FROM ErrorMessage em
INNER JOIN UserLanguages l ON em.Language=l.LanguageID
WHERE ErrorCode = pErrorCode
ORDER BY l.LanguageOrder LIMIT 1;
like image 69
Frank Schnabel Avatar answered Oct 09 '22 18:10

Frank Schnabel