簡體   English   中英

合並 SQL 中的 json 中沒有公共列的兩個表

[英]merge two tables without common column in a json in SQL

我有 2 個表格,例如table1 (column1,column2)插入了多行, table2(column3,column4,column5,column6)只有一個。 是否可以合並一個 json 字符串? 我嘗試 select 與 json Auto 但我不能確保不重復表 2 的行數表 1 的行數

我想要的結果是這樣的:

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

您尚未指定要使用的 SQL 版本,但是,如果您使用的是 MS SQL 服務器,則可以達到您想要的結果,如下所示:

-- 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM