Home >Database >Mysql Tutorial >How can you join MySQL tables based on data within a JSON field?
Using MySQL JSON Field for Complex Table Joins
Problem:
In a MySQL database schema, a JSON field stores a list of IDs. The goal is to perform operations on this JSON field and use the results in an SQL query to join the user table with a user group table.
Example Scenario:
Consider the following tables:
CREATE TABLE user ( user_id INT, user_name VARCHAR(50), user_groups JSON ); CREATE TABLE user_group ( user_group_id INT, group_name VARCHAR(50) );
With the following data:
INSERT INTO user_group (user_group_id, group_name) VALUES (1, 'Group A'); INSERT INTO user_group (user_group_id, group_name) VALUES (2, 'Group B'); INSERT INTO user_group (user_group_id, group_name) VALUES (3, 'Group C'); INSERT INTO user (user_id, user_name, user_groups) VALUES (101, 'John', '[1,3]');
Desired Result:
The desired result is a query that retrieves the following data:
user_id | user_name | user_group_id | group_name| ------------------------------------------------- 101 | John | 1 | Group A 101 | John | 3 | Group C
Solution:
The solution involves using the JSON_CONTAINS function to check if the user group ID exists within the JSON field of the user table.
<code class="sql">SELECT u.user_id, u.user_name, g.user_group_id, g.group_name FROM user u LEFT JOIN user_group g on JSON_CONTAINS(u.user_groups, CAST(g.user_group_id as JSON), '$')</code>
Note:
The $ operator in the JSON_CONTAINS function represents the root of the JSON document.
The above is the detailed content of How can you join MySQL tables based on data within a JSON field?. For more information, please follow other related articles on the PHP Chinese website!