Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: inner join on alias column

Tags:

sql

inner-join

Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.

So I have this:

SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) 
AS 'memId',  userDetails.title, userDetails.lname 
FROM accountingTab INNER JOIN
(SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id

And then I get the Invalid Column Name memID error.

How can I fix this?

like image 671
Symbioxys Avatar asked Mar 01 '23 07:03

Symbioxys


2 Answers

You can either repeat the whole expression or reverse your join:


SELECT *
FROM memDetTab
    JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname
FROM accountingTab) subquery
    ON subquery.memID = memDetTab.ID
like image 119
Chris Shaffer Avatar answered Mar 03 '23 21:03

Chris Shaffer


Instead of memId, repeat the whole expression.

like image 38
Milan Babuškov Avatar answered Mar 03 '23 21:03

Milan Babuškov