Skip to content

Instantly share code, notes, and snippets.

@Mevrael
Last active January 11, 2024 16:58
Show Gist options
  • Select an option

  • Save Mevrael/bc645cb63a2d3bbae3fb43366b47f313 to your computer and use it in GitHub Desktop.

Select an option

Save Mevrael/bc645cb63a2d3bbae3fb43366b47f313 to your computer and use it in GitHub Desktop.
MySQL 5.7 JOIN on JSON column of IDs
```mysql
SELECT u1.id AS id1, u2.id AS id2 FROM users AS u1 JOIN users AS u2 ON JSON_CONTAINS(u1.friends, CAST(u2.id AS CHAR))
```
@teol
Copy link

teol commented Jun 21, 2018

Thanks for sharing this

@donpaul120
Copy link

I'm trying to do something similar but in my case the like value is like
[{"id":1, date_liked:date}, {id:2, date_liked:date}]

I tried doing this
LEFT JOIN users g on JSON_CONTAINS(posts.liked, CAST(g.id as JSON), '$[*].id')

But it says :

In this situation, path expressions may not contain the * and ** tokens or an array range.

Do you have any idea how this can be done? Please

@donpaul120
Copy link

I think I figured it out.. just incase

LEFT JOIN users g on JSON_CONTAINS(posts.liked->'$[*].id', CAST(g.id as JSON))

@asciirobot
Copy link

@stevenwadejr
Copy link

I was just stuck on this and this gist had exactly what I needed to fix it. Thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment