'select query for one-to-many relations table
I have 2 tables. These two tables have one-to-many relations.
TABLE - A
column1 column2
1 label1
2 label2
TABLE - B
Bcolumn1 Bcolumn2 Bcolumn3
1 value1 value4
1 value2 value5
2 value3 value6
RESULT TABLE
column1 column2 json
1 label1 [{"Bcolumn":value1,"Bcolumn":value4},{"Bcolumn":value2,"Bcolumn":value5}]
2 label2 [{"Bcolumn":value3,"Bcolumn":value6}]
I want to get RESULT TABLE1 using TABLE - A and TABLE - B.
how can I get this result?
Thank you.
Solution 1:[1]
What you are looking for in sqlite is the group_concat() function. It's tricky, cause you have he values you want to concat in 2 different columns. Basically you can do the following
select
a.column1
, a.column2
, '[{' || group_concat('"Bcolumn":' || b.bcolumn2 || '"Bcolumn":' || b.bcolumn3,'};{') || '}]' as json_output
from tablea a
inner join tableb b on
a.column1 = b.bcolumn1
group by
a.column1
, a.column2
;
I tested this solution with MSSQL 2019 and string_agg(), but from the documentation (https://www.sqlitetutorial.net/sqlite-group_concat/) this should work just as well in sqlite.
The trick is to use '};{' as separator, because like this, you will only have to care about the opening and closing brackets and nothing in the middle.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
