SQL json extract where in array

Viewed 359

I have users table with json type attributes column:

Example value:

attributes: {"connection": "HTTP"},
attributes: {"connection": "API"}

When I tried get using WHERE IN() with one param all works correctly:

SELECT * FROM users WHERE JSON_EXTRACT(attributes, '$.connection') IN ("HTTP");

But when I tried with multiple value it's doesn't work for me:

SELECT * FROM users WHERE JSON_EXTRACT(attributes, '$.connection') IN ("API", "HTTP");

In this case return nothing. How I can get users which has one of defined connections inside WHERE IN() values?

1 Answers

In MySQL 5.7 (possibly only later 5.7 versions; I saw some indications that some JSON_EXTRACT behavior changed in 5.7.10 or 5.7.11), it does not appear to cast the JSON value returned by JSON_EXTRACT to a string when used as the left operand to IN. This will work in both 5.7 and 8.0:

SELECT * FROM users WHERE JSON_UNQUOTE(JSON_EXTRACT(attributes, '$.connection')) in ('HTTP','API');

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=ea3e311a775cf30e393b6ac07b7fde30

Related