将JSON类型的列与特定字符串值进行比较

huangapple go评论53阅读模式
英文:

Comparing JSON-typed column with specific string value

问题

我有以下的表格:

```sql
CREATE TABLE mytable (
    id     int, 
    name   varchar(255), 
    data   json
);
id name data
1 John ["a", "b"]
2 Pete ["a", "b", "c"]
3 Mike ["a", "b"]

其中 data 列具有 JSON 类型,并且我想选择字段 data 等于字符串 ["a", "b"] 的行。

我目前正在使用的简单方法是:

SELECT * FROM mytable WHERE data = '["a", "b"]'

然而,它总是返回空集。什么是正确比较 JSON 字段与字符串的方法?


<details>
<summary>英文:</summary>

I have following table:

CREATE TABLE mytable (
id int,
name varchar(255),
data json
);


| id | name | data            |
|----|------|-----------------|
| 1  | John | [&quot;a&quot;, &quot;b&quot;]      |
| 2  | Pete | [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] |
| 3  | Mike | [&quot;a&quot;, &quot;b&quot;]      |

Where column `data` has `JSON` type, and I want to select rows where field `data` equal to string `[&quot;a&quot;, &quot;b&quot;]`.

Naive approach I&#39;m currently using:

```sql
SELECT * FROM mytable WHERE data = &#39;[&quot;a&quot;, &quot;b&quot;]&#39;

Yet it always returns empty set. What is right way to compare JSON fields with strings?

答案1

得分: 2

使用JSON_ARRAY()函数创建一个JSON数组,然后与之比较。

SELECT * FROM mytable WHERE data = JSON_ARRAY('a', 'b');

演示

英文:

Use the JSON_ARRAY() function to create a JSON array, and compare with this.

SELECT * FROM mytable WHERE data = JSON_ARRAY(&#39;a&#39;, &#39;b&#39;);

DEMO

答案2

得分: 2

你可以使用CAST(... AS JSON)将JSON字符串转换为JSON数据类型以进行比较:

SELECT *
FROM t
WHERE data = CAST('[
  "a",
  "b"
]' AS JSON)
英文:

You can use CAST(... AS JSON) to convert the JSON-as-string to JSON data type for comparison:

SELECT *
FROM t
WHERE data = CAST(&#39;[
  &quot;a&quot;,
  &quot;b&quot;
]&#39; AS JSON)

huangapple
  • 本文由 发表于 2023年6月1日 04:20:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定