SQL Server 2016 过滤器里面 json_value
SQL Server 2016 filter inside json_value
我有一个feeds
table有一个json数组列(UserLike
)的人喜欢它。 Table 会像:
FeedID FeedName UserLike
1 Feed 1 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
2 Feed 2 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
3 Feed 3 [{"UserID":1,"UserName":"User 1"}]
我想通过比较UserID
(如果他喜欢,或者不喜欢return UserLike null,我想获得提要行,即使登录用户不在 UserLike
列表中)。
我该怎么做? T-SQL 是否支持以下内容:
select
FeedID, FeedName,
Json_value(UserLike, '$[UserID=1].UserName')...
我期待的结果是:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL
使用 WHERE 子句:UserID=2
--Here we take all feeds
;WITH cte AS (
SELECT DISTINCT FeedID,
FeedName
FROM dbo.feeds
--Here we take parsed JSON
), feeds AS (
SELECT FeedID,
FeedName,
UserID,
UserName
FROM [dbo].[feeds] f
CROSS APPLY OPENJSON ([UserLike])
WITH (
UserID int,
UserName nvarchar(255)
))
--And here we join them
SELECT c.FeedID,
c.FeedName,
f.UserID,
f.UserName
FROM cte c
LEFT JOIN feeds f
ON f.FeedID = c.FeedID and f.UserID = 2
输出:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL
我有一个feeds
table有一个json数组列(UserLike
)的人喜欢它。 Table 会像:
FeedID FeedName UserLike
1 Feed 1 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
2 Feed 2 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
3 Feed 3 [{"UserID":1,"UserName":"User 1"}]
我想通过比较UserID
(如果他喜欢,或者不喜欢return UserLike null,我想获得提要行,即使登录用户不在 UserLike
列表中)。
我该怎么做? T-SQL 是否支持以下内容:
select
FeedID, FeedName,
Json_value(UserLike, '$[UserID=1].UserName')...
我期待的结果是:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL
使用 WHERE 子句:UserID=2
--Here we take all feeds
;WITH cte AS (
SELECT DISTINCT FeedID,
FeedName
FROM dbo.feeds
--Here we take parsed JSON
), feeds AS (
SELECT FeedID,
FeedName,
UserID,
UserName
FROM [dbo].[feeds] f
CROSS APPLY OPENJSON ([UserLike])
WITH (
UserID int,
UserName nvarchar(255)
))
--And here we join them
SELECT c.FeedID,
c.FeedName,
f.UserID,
f.UserName
FROM cte c
LEFT JOIN feeds f
ON f.FeedID = c.FeedID and f.UserID = 2
输出:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL