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
code:"ER_BAD_FIELD_ERROR" errno:1054 sqlMessage:"Unknown column 'loanType' in 'on clause'" sqlState:"42S22"
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.
Advertisement
Answer
Either repeat the expression in the ON
clause, or join with a subquery.
SELECT c.applicationDateTime, c.loanType, l.financingType FROM ( 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.