SQL Server 2016 select 其中 json 具有正常 table 的对象数组

SQL Server 2016 select where in json array of objects with normal table

请帮助我 sql 查询以完成以下要求

我想加入一个 table 与另一个 table 有一个 JSON 列与两个字符串列比较。

这个查询是针对 Azure SQL DB 我想加入 Table 2 和 Table 1

它应该满足以下2个条件 Table2.Items(每个项目)。product_category = Table1.product_category 和 Table2.Items(每个项目)。product_id = Table1.product_id

并希望将 Table 中的所有项目和列扩展为行 JSON 中的每个项目到行

Table 1

product_category    product_name    product_id  product_cost
Gift                Glass           157         85
Electronics         Bulb            833         218
Kitchen             Glass           157         75

Table 2

Order_ID    Pincode Order_details   Email
HASDUI2N342 766815  <JSON_Data>     user1@domain.com
ASDIJ234HJI 487957  <JSON_Data>     user2@domain.com
ASDOI23480H 512878  <JSON_Data>     user2@domain.com

样本 <JSON_Data> order_id HASDUI2N342

{
  "order_date": "26-07-2019",
  "Items": [
    {
      "product_category": "Gift",
      "product_id": "157"
    },
    {
      "product_category": "Electronics",
      "product_id": "833"
    }
  ],
  "amount_paid": 333,
  "shipping" :  30

}

下面是加入两者后的预期结果Table

Order_ID    Pincode Email               Item.product_Name   Item.product_cost
HASDUI2N342 766815  user1@domain.com    Glass               85
HASDUI2N342 766815  user1@domain.com    Bulb                218
ASDIJ234HJI 487957  user2@domain.com    .....               ....
ASDIJ234HJI 487957  user2@domain.com    .....               ....
ASDOI23480H 512878  user3@domain.com    .....               ....

您需要将 OPENJSON() 与明确的模式定义和适当的连接结合使用:

表格:

CREATE TABLE Table1 (
   product_category nvarchar(50),
   product_name nvarchar(50),    
   product_id int,  
   product_cost int
)
INSERT INTO Table1
   (product_category, product_name, product_id, product_cost)
VALUES   
   (N'Gift'        , N'Glass', 157, 85),
   (N'Electronics' , N'Bulb' , 833, 218),
   (N'Kitchen'     , N'Glass', 157, 75)
CREATE TABLE Table2 (
   Order_ID nvarchar(100),
   Pincode int,
   Order_details nvarchar(max),
   Email nvarchar(100)
)
INSERT INTO Table2
   (Order_ID, Pincode, Order_details, Email)
VALUES
   (
   N'HASDUI2N342',
   766815,
   N'{
  "order_date": "26-07-2019",
  "Items": [
    {
      "product_category": "Gift",
      "product_id": "157"
    },
    {
      "product_category": "Electronics",
      "product_id": "833"
    }
  ],
  "amount_paid": 333,
  "shipping" :  30
   }',
   N'user1@domain.com'
   )

声明:

SELECT 
   t2.Order_ID, t2.Pincode, t2.Email,
   t1.product_name, t1.product_cost
FROM Table2 t2
CROSS APPLY OPENJSON(t2.Order_details, '$.Items') WITH (
   product_id nvarchar(100) '$.product_id',
   product_category nvarchar(100) '$.product_category'
) j
LEFT JOIN Table1 t1 ON (j.product_id = t1.product_id) AND (j.product_category = t1.product_category)

输出:

Order_ID    Pincode Email               product_name    product_cost
HASDUI2N342 766815  user1@domain.com    Glass           85
HASDUI2N342 766815  user1@domain.com    Bulb            218