Sql-Server

具有 json 的欄位上的高效 where 子句

  • December 6, 2021

我有以下查詢,我想在 json 欄位上添加 where 子句,下面是我的 json,我根據類別列表過濾掉,在下面的範例中,有 3 個類別,如果我傳入 7,9,我希望將以下記錄包含在我的列表中。

我想我不確定我的 json where 子句會是什麼樣子並且有效

TSql

SELECT TOP 1 *
 FROM Tweets                                
 WHERE IsProcessed = 0 AND HasEvents = 1
 AND --Json filter
 ORDER BY TweetDate DESC

json

{
  "Dates":{
     "DateTimeResults":[
        {
           "DateTime":"2014-03-20T00:00:00-04:00",
           "UtcOffsetMinutes":0,
           "Text":"today",
           "Timex":"2014-03-20"
        }
     ]
  },
  "Categories":[
     7,
     9,
     12
  ]
}

像這樣的東西:

use tempdb
go
create table Tweets(Message nvarchar(1024), IsProcessed bit, HasEvents bit, Details nvarchar(max))

insert into Tweets(Message,IsProcessed,HasEvents,Details)
           values ('foo',0,1,N'
           {
  "Dates":{
     "DateTimeResults":[
        {
           "DateTime":"2014-03-20T00:00:00-04:00",
           "UtcOffsetMinutes":0,
           "Text":"today",
           "Timex":"2014-03-20"
        }
     ]
  },
  "Categories":[
     7,
     9,
     12
  ]
}')

go

declare @categories nvarchar(max) = '[7,9]'

select *
from Tweets t
where (select count(distinct value) from openjson(@categories) ) =
     (
      select count(distinct value) 
      from  openjson (t.Details, '$.Categories')  c
      join openjson(@categories) rc
       on c.value = rc.value 
      )   

可以將類別保存為計算列,如下所示:

create table Tweets
(
 Message nvarchar(1024), 
 IsProcessed bit, 
 HasEvents bit, 
 Details nvarchar(max), 
 Categories as json_query(Details,'$.Categories') persisted
)

但我不確定這是否會更有效。

引用自:https://dba.stackexchange.com/questions/303586