Home > Software design >  select query for one-to-many relations table
select query for one-to-many relations table

Time:02-17

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 TABLE using TABLE - A and TABLE - B.

how can I get this result?

Thank you.

CodePudding user response:

Use SQLite's JSON1 Extension functions:

SELECT a.column1, a.column2,
       json_group_array(json_object('Bcolumn', b.Bcolumn2, 'Bcolumn', b.Bcolumn3)) json
FROM tableA a INNER JOIN tableB b
ON b.Bcolumn1 = a.column1
GROUP BY a.column1;

See the demo.

CodePudding user response:

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.

  • Related