0

I have a JSON Array field on table A, I want to read the relevant descriptions from another table B. Example: Table A,

id types
1 [C,B,T]

Table B,

type description
C Car
B Bus
T Train

While reading data from table A, I want the result should be,

id types
1 [Car, Bus, Train]

Can anyone help me with MySQL query to achieve this?

4
  • The end output would be on a web/app page? What MySQL version? Commented Oct 4, 2021 at 7:46
  • @FaNo_FN Query output should be like I mentioned above. MySQL Version: 8.0.23. Commented Oct 4, 2021 at 8:17
  • You mean that the types output will retain it's JSON array format right? What I'm curious is the end output and how it's going to be used. I mean, will it end up in a report? Commented Oct 4, 2021 at 9:03
  • @FaNo_FN Sorry, I couldn't understand your question. The intention is to display the actual description of the types on the UI. For that, if I write a query like "SELECT * FROM A", I will get [C, B, T]. This is not understandable in UI. So I want to map [C, B, T] to table B and read the description and return it. Commented Oct 4, 2021 at 10:00

2 Answers 2

1

Try this one:

    CREATE TABLE `a` (
      `id` int DEFAULT NULL,
      `type` json DEFAULT NULL
    ) ENGINE=InnoDB;

    INSERT INTO `a` VALUES (
      1, '["C", "B", "T"]'
    );

    CREATE TABLE `b` (
      `type` varchar(8) DEFAULT NULL,
      `description` varchar(16) DEFAULT NULL
    ) ENGINE=InnoDB;

    INSERT INTO b VALUES 
      ("C", "Car"),
      ("B", "Bus"),
      ("T", "Train")  ;



    SELECT d.id, CONCAT('[', GROUP_CONCAT(b.description), ']') AS result FROM (
    SELECT id, `c`.`type`
    FROM a,
    JSON_TABLE(`type`, '$[*]'
    COLUMNS(
       `type` VARCHAR(32) PATH '$'))
    AS c) AS d INNER JOIN b ON (`d`.`type` = `b`.`type`);

Result:

    |  id  |   result |
    -------| ----------
    
    '1', '[Car,Bus,Train]'
    
Sign up to request clarification or add additional context in comments.

Comments

0

This query will return your output.

SELECT tb.id, concat('[', group_concat(tb.description), ']') FROM table_b tb
WHERE tb.type in (SELECT data_set.types FROM (select SUBSTRING(types, 1, 11) AS TYPES from table_a) AS data_set)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.