【发布时间】:2021-06-16 05:01:36
【问题描述】:
我有一个数据库,其中包含一个产品表和一个键值对表,用于将随机数据与每个产品相关联。
- 产品表:productId(pk),名称
- ProductDetails 表:productId(fk)、名称、值
我想运行类似这样的查询:
SELECT
*,
(???) as details
from Products p
JOIN ProductDetails pd on pd.productId = p.productId
WHERE (??? there exists a value with pd.key = 'foo' and pd.value like '%bar%` ???)
我想取回如下所示的数据:
productID name details
----------- ----------- -----------------------------------------------------------
22 flizbot {"sponsor": "fred", "foo", "casbar", "planet": "venus"}
354 munchbat {"foo": "barrel", "power": "over9000"}
...
我该如何编写这样的查询?
【问题讨论】:
-
在提出问题时,您需要提供一个可重现的最小示例:(1) DDL 和样本数据填充,即 CREATE 表加上 INSERT、T-SQL 语句。 (2) 你需要做什么,即逻辑,以及你在 T-SQL 中的尝试实现。 (3) 基于上述#1 中的样本数据的期望输出。 (4) 你的 SQL Server 版本 (SELECT @@version;)
-
这能回答你的问题吗? Convert select query results into Json
-
@devlincarnate 不相关,因为 JSON 键需要是动态的,而 SQL 无法做到这一点
-
@Charlieface :我很好奇您是如何知道 json 键需要根据 OP 发布的内容动态变化的。
-
@devlincarnate
{"foo": "barrel"和pd.key = 'foo' and pd.value like '%bar%`` seems quite clear to me that keyfoo` 是动态的,因为它来自key列
标签: sql sql-server key-value