简体   繁体   中英

merge two tables without common column in a json in SQL

i have 2 tables like table1 (column1,column2) with multiple rows inserted and table2(column3,column4,column5,column6) with just one. Is possible to merge in one json string? i Try select with for json Auto but I can't make sure not to repeat the row of table 2 for the number of rows of table 1

the result I would like is this:

{"Table1Name" :[{"column1":1,"column2":2},{"column1":3,"column2":4},{"column1":5,"column2":6}],"column3":a,"column4":b,"column5":c,"column6":d}

You haven't specified what version of SQL you want to use, however if you're using MS SQL Server you can achieve your desired results like so:

-- Creating tables to simulate your data
DECLARE @table1 as table (column1 int, column2 int)
DECLARE @table2 as table (column3 char(1), column4 char(1), column5 char(1), column6 char(1))

INSERT INTO @table1
VALUES (1, 2), (3, 4), (5, 6)

INSERT INTO @table2
VALUES ('a', 'b', 'c', 'd')

-- Use FOR JSON AUTO to reduce the results from Table1 into a single value before cross joining to Table2
SELECT *
FROM (
    SELECT *
    FROM @table1
    FOR JSON AUTO
) AS A(Table1Name)
CROSS JOIN @table2 AS B
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM