简体   繁体   中英

In MySQL having issues while fetching data from two tables via performing joining on JSON column

I have two tables users and usergroups and there is no hard relationship between them. users table contains an usergroup column which holds multiple usergroup_id from usergroups table in JSON format and usergroups table contains id and usergroup_title columns. Now the requirement is to get the list of all users via a single query which should contain the user data, usergroup_title from usergroups table corresponding to the JSON values.

I had tried with the below query but I am getting an error that JSON_CONTAINS function does not exists. The code is below:

SELECT 
u.user_id,
g.id,
g.usergroup_title
FROM user u
LEFT JOIN usergroups g on JSON_CONTAINS(u.usergroup_id, CAST(g.id as JSON), '$')

I am getting an error JSON_CONTAINS function does not. I want the data in below format:

array("user_id" => 1, "usergroup" => ["admin", "customer", "seller"])

Since we know it's a horrible way to deal with many to one relation, let's get on with the dirt :

SELECT 
u.user_id,
g.id,
g.usergroup_title
FROM user u
LEFT JOIN usergroups g on u.usergroup_id LIKE CONCAT('%"',g.id,'"%')

It should do the trick IF your ids are treated as string in your JSON, else you'll need to replace the '%"' and '"%' parts with something like '%:' and ',%' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM