[英]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.
users表包含一个usergroup列,其中以JSON格式保存了usergroups表中的多个usergroup_id,而usergroups表则包含id和usergroup_title列。 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.
现在,要求是通过一个查询获取所有用户的列表,该查询应包含用户数据(来自与JSON值相对应的usergroups表中的usergroup_title)。
I had tried with the below query but I am getting an error that JSON_CONTAINS function does not exists. 我曾尝试使用以下查询,但收到错误消息JSON_CONTAINS不存在。 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. 我收到一个错误JSON_CONTAINS函数没有。 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 ',%'
. 如果您的ID在JSON中被视为字符串,那么它应该可以解决问题,否则您需要用
'%:'
和',%'
等替换'%"'
和'"%'
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.