0

I have following id in column

 [1,2]

which the account of ID 1 is Kenvin, and ID2 is Charles How can i get the info like this in a new column:

['Kenvin','charles']

table A

id account
1 kenvin
2. charles

table B

id title target table_a_ids
1 abc 4 [1,2]
2 xyz 1 []
3 ggg 4 [2]

target output: (add a display columns as table_a_accounts in table B)

id title target table_a_ids table_a_accounts
1 abc 4. [1,2] ['kenvin','charles']
2 xyz 1 [] []
3 ggg 4 [2] ['charles']
4
  • Convertion not needed. WHERE table2.id MEMBER OF table1.array Commented Jun 16, 2022 at 16:30
  • @Akina nono.. for example.. in table1, column id >>1 , 2, column name >> kenvin, charles. in table 2, column id >> 1, column target_id >> [1,2]. How can i get a new column in table 2 which display as ['kenvin','charles'] Commented Jun 16, 2022 at 16:49
  • Show this everything in the question text. As code-formatted CREATE TABLE + INSERT INTO, and desired output as formatted table. Commented Jun 16, 2022 at 17:37
  • @Akina please take a look again Commented Jun 17, 2022 at 3:24

1 Answer 1

1
SELECT B.id, B.title, B.target, B.table_a_ids, 
       JSON_ARRAYAGG(A.account) table_a_accounts
FROM B
LEFT JOIN A ON A.id MEMBER OF (B.table_a_ids)
GROUP BY B.id, B.title, B.target, B.table_a_ids

If your server is 5.7 then use

SELECT B.id, B.title, B.target, B.table_a_ids, 
       JSON_ARRAYAGG(A.account) table_a_accounts
FROM B
LEFT JOIN A ON JSON_CONTAINS(CAST(B.table_a_ids AS JSON), CAST(A.id AS JSON))
GROUP BY B.id, B.title, B.target, B.table_a_ids

If B.table_a_ids is JSON datatype then remove according CAST().

https://dbfiddle.uk/?rdbms=mysql_8.0&rdbms2=mysql_5.7&fiddle=9aaac43c22b4d82d2752df8d87f221a0

If [null] is not safe for you then use REPLACE().

Sign up to request clarification or add additional context in comments.

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.