1

I have a JSON column that might contain the string "attribute":"my_value" (among other JSON properties), this is the query I have to search for it:

SELECT 1 
FROM TABLE 
WHERE JSON_COLUMN REGEXP '"attribute":"?"'

The execQuery function adds an apostrophe to the parametrized string and this is the query that runs:

SELECT 1 
FROM TABLE 
WHERE JSON_COLUMN REGEXP '"attribute":"'my_value'"'

This is not a valid SQL query, how can I search for this parameter to get the rows that match this value?

I am using orm package for mysql (5.6) in nodejs, this is how I use it:

execQuery(MY_QUERY, [param1], (err, data) => {
            if (err) {
                return reject({
                    error: 'cannotFetch',
                    message: err
                });
            } else {
                return resolve(data);
            }
        })

3 Answers 3

2

If you have a JSON column, why wouldn't you just extract the value?

WHERE JSON_COLUMN->'$.attribute' = 'myvalue' 
Sign up to request clarification or add additional context in comments.

Comments

2

you can use JSON_EXTRACT to use JSON column in where clause

WHERE JSON_EXTRACT(JSON_COLUMN, "$.attribute") = 'myvalue'

edit:

if you use mysql 5.6 or less you must use REGEXP

WHERE  `JSON_COLUMN` REGEXP  '"attribute":[^}]*"my_value"[^}]*}'

db-fiddle

6 Comments

i checked my mysql version and i have 5.6.34 so it seem i cannot use that
my problem is that the parametized string is being sent with apostrophes so it sends '"attribute":[^}]*" 'my_value' "[^}]*}' , do you know if there is there any way to remove it?
@Anna24 you must use backslash before quote (\')
it does make the query valid ,however now it won't match the regex query [db-fiddle.com/f/bW2HFSfEh4DQJGNqL8n8pX/3] i think i will send the parameter the whole regex string instead of trying to use it only on the value , perhaps there is no neat way of doing that in versions before 5.7 thanks for your help
@Anna24 In the fiddle you sent, the table contents there is no quotes you entered in the query quotes, see this fiddle
|
1

I ended up using the following query instead:

const MY_QUERY = `SELECT 1 FROM TABLE WHERE JSON_COLUMN REGEXP ?`;

And took care of the dynamic value in the nodejs part :

const getAttributeUsageTemplate = value => (`"attribute":"${value}"`);

execQuery(MY_QUERY, [getAttributeUsageTemplate(param1)], (err, data) => {
})

this is the only solution i found for my version of mysql
the driver still surrounds the parameter with apostrophes but they don't get in the way of the regular expression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.