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

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

Comparing JSON-typed column with specific string value

问题

  1. 我有以下的表格:
  2. ```sql
  3. CREATE TABLE mytable (
  4. id int,
  5. name varchar(255),
  6. data json
  7. );
id name data
1 John ["a", "b"]
2 Pete ["a", "b", "c"]
3 Mike ["a", "b"]

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

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

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

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

  1. <details>
  2. <summary>英文:</summary>
  3. I have following table:

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

  1. | id | name | data |
  2. |----|------|-----------------|
  3. | 1 | John | [&quot;a&quot;, &quot;b&quot;] |
  4. | 2 | Pete | [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] |
  5. | 3 | Mike | [&quot;a&quot;, &quot;b&quot;] |
  6. Where column `data` has `JSON` type, and I want to select rows where field `data` equal to string `[&quot;a&quot;, &quot;b&quot;]`.
  7. Naive approach I&#39;m currently using:
  8. ```sql
  9. 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数组,然后与之比较。

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

演示

英文:

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

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

DEMO

答案2

得分: 2

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

  1. SELECT *
  2. FROM t
  3. WHERE data = CAST('[
  4. "a",
  5. "b"
  6. ]' AS JSON)
英文:

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

  1. SELECT *
  2. FROM t
  3. WHERE data = CAST(&#39;[
  4. &quot;a&quot;,
  5. &quot;b&quot;
  6. ]&#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:

确定