我在我的 MySQL 数据库 json 字段中存储了一些 json 数组。
例如:["Python", "C", "C++", "C#", "R"]
我的数据库的一个例子:
| name | techs |
|--------|------------------|
| victor | ["Python", "R"] |
| anne | ["C#", "Python"] |
我需要搜索 json 数组至少包含另一个 json 数组的一项的行。问题出在我正在执行的查询中:
select name from devs
where json_contains('techs', '["Python"]')
这实际上工作正常并返回数组包含“Python”的所有行(在这个例子中,[Victor, Anne]),但是当我尝试传递不存在于任何数组中的项目时:
select * from devs
where json_contains('techs', '["Python", "Java"]')
这没有返回任何内容,因为没有包含“Python”和“Java”的数组。也许,我想在他们的 json 数组中接收所有带有“Python”或“Java”的行。
这样,有没有语法可以按照我想要的方式返回数据?
提前致谢。
有用信息: MySQL:v8.0,在 Windows 10 上运行。
最佳答案
MySQL 8.0 具有函数 JSON_OVERLAPS() ,这正是您所要求的:
Compares two JSON documents. Returns true (1) if the two document have any key-value pairs or array elements in common.
When two comparing two arrays, JSON_OVERLAPS() returns true if they share one or more array elements in common, and false if they do not.
您可以在自连接查询中使用它,例如:
select t.*
from mytable t
inner join mytable t1 on json_overlaps(t1.techs, t2.techs)
关于mysql - 有没有办法检查一个 json 数组是否至少包含 MySQL 中另一个 json 数组的一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846109/