Skip to content

SQL Join ON clause valid referencing on aliases

I am generating an SQL query and I need to get the data from a JSON stored on a field of my table. It goes something like this

SELECT creation.INSERT_DATE as applicationDateTime,
REPLACE(json_extract(creation.FACILITY_DATA, '$.loanType'), '"', '') AS loanType,
lookup_detail.DETAIL_DESCRIPTION AS financingType 
FROM creation 
LEFT JOIN lookup_detail ON lookup_detail.DETAIL_CODE = loanType

So basically I am trying to get put a connection with tables creation and lookup_detail through field FACILITY_DATA which has JSON data and alias of loanType to reference against DETAIL_CODE field. However, I get this error

sqlMessage:"Unknown column 'loanType' in 'on clause'"

Is there anything I could do to work on this? I tried to search what are the valid reference to ON clause of JOIN operation, but I only get the typical ways.



Either repeat the expression in the ON clause, or join with a subquery.

SELECT c.applicationDateTime, c.loanType, l.financingType
    SELECT INSERT_DATE as applicationDateTime,
            REPLACE(json_extract(creation.FACILITY_DATA, '$.loanType'), '"', '') AS loanType
    FROM creation
) AS c
JOIN lookup_detail AS l ON l.DETAIL_CODE = c.loanType

Also, you probably should be using JSON_UNQUOTE() rather than REPLACE(). Or you can use the ->> operator, which extracts and unquotes in one step.

User contributions licensed under: CC BY-SA
5 People found this is helpful