Sql链接其他表作为一列

时间:2016-08-09 09:18:01

标签: sql-server azure-sql-database

我有下表Table1:

id │ value_one │  
───┼───────────┼
1  │ a         │         
2  │ b         │     

表2:

id │ value_two │ table1_id │ value_three
───┼───────────┼───────────┼───────
1  │ a1        │ 1         │ a2
2  │ b1        │ 1         │ b2

我想获得如下结果,将table2_ table = _1 = 1的table2绑定到列中作为列

{
 "value_one":"a",
 "from_table2":[
 {"value_two":"a1","value_three":"a2"},  
 {"value_two":"b1","value_three":"b2"}
 ]            
}

我应该使用哪个SQL(sql server)查询?

@@抱歉,我使用... azure SQL Database .....

(Azure SQL数据库V12的兼容级别从130开始,与Microsoft SQL Server 2016 GA匹配。)

并希望在nodejs中使用查询字符串。

var queryString = "";
var query = {
  sql: queryString
};
req.azureMobile.data.execute(query)

1 个答案:

答案 0 :(得分:0)

我有可能在SQL Server 2016中测试解决方案,但可以在早期版本的SQL Server中执行以下操作:

WITH Table1 AS
(
    SELECT * FROM (VALUES
    (1, 'a'),
    (2, 'b')) T(id, value_one)
), Table2 AS
(
    SELECT * FROM (VALUES
    (1, 'a1', 1, 'a2'),
    (2, 'b1', 1, 'b2')
    ) T(id, value_two, table1_id, value_three)
), RowValues AS
(
    SELECT '{"value_one":'+QUOTENAME(value_one, '"')+',"from_table2":['+
        STUFF((SELECT ',{"value_two":'+QUOTENAME(value_two, '"')+',"value_three":'+QUOTENAME(value_three, '"')+'}'
        FROM Table2
        WHERE T1.id=table1_id
        FOR XML PATH('')), 1, 1, '')
        +']}' RowValue
    FROM Table1 T1
)
SELECT *
FROM RowValues
WHERE RowValue IS NOT NULL

它产生:

{"value_one":"a","from_table2":[{"value_two":"a1","value_three":"a2"},{"value_two":"b1","value_three":"b2"}]}

SQL Server 2016,FOR JSON

WITH Table1 AS
(
    SELECT * FROM (VALUES
    (1, 'a'),
    (2, 'b')
    ) T(id, value_one )
), Table2 AS
(
    SELECT * FROM (VALUES
    (1, 'a1', 1, 'a2'),
    (2, 'b1', 1, 'b2')
    ) T(id, value_two, table1_id, value_three)
)
SELECT R FROM Table1 T1
CROSS APPLY
(
    SELECT T1.value_one,
        (SELECT value_two, value_three FROM Table2 WHERE table1_id=T1.id FOR JSON PATH) fromTable2
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) T(R)
--WHERE id=1--optional filter

将整个结果作为一个JSON包含起来会更容易,但它似乎违背了您的假设。