Mysql - 如何比较两个Json对象?

时间:2017-06-26 19:23:09

标签: mysql json

将整个MySql json列与json对象进行比较的语法是什么?

以下不起作用:

select count(criteria) from my_alerts where criteria = '{"industries": ["1"], "locations": ["1", "2"]}'

即使条件列的值为{"industries": ["1"], "locations": ["1", "2"]}

,我也会得到0

如果我错了,请纠正我,但如果两个JSON对象具有相同的密钥集,则两个JSON对象相等,并且每个密钥在两个对象中具有相同的值。键和值的顺序将被忽略。所以以下内容应该相同?

 {"industries": ["1"], "locations": ["1", "2"]} = {"locations": ["2", "1"], "industries": ["1"]}

*更新*

我已经设法通过如下投射到json来实现它:

select count(criteria) from my_alerts where criteria = CAST('{"industries": ["1"], "locations": ["1", "2"]}' AS JSON)

然而,在比较期间忽略了键的顺序,仍然比较值的顺序。所以以下是假的:

{"locations": ["1", "2"]} = {"locations": ["2", "1"]}

有没有办法强制比较忽略值的顺序?

3 个答案:

答案 0 :(得分:4)

您可以使用JSON_CONTAINS进行此操作:

SELECT COUNT(criteria) 
FROM my_alerts 
WHERE JSON_CONTAINS(criteria,'{"industries": ["1"], "locations": ["1", "2"]}')

此操作执行的比较忽略了值的顺序,这很重要,因为MySQL会对JSON属性重新排序以提高INSERT的效率。

答案 1 :(得分:1)

您可以使用CAST()功能:

SELECT count(criteria)
FROM my_alerts 
WHERE criteria = CAST('{"industries": ["1"], "locations": ["1", "2"]}' AS JSON)

答案 2 :(得分:0)

如果您使用的是MySQL 5.7.8或更高版本,则应该能够使用以下语法将json列与json对象进行比较。插入的键值对的顺序无关紧要。

SELECT json_col = JSON_OBJECT('foo', 'bar', 'color', 'red') FROM table1;

通过创建下表对此进行测试:

CREATE TABLE IF NOT EXISTS `mydb`.`table1` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `json_col` JSON NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

将数据插入表中。注意最后插入的行中的颠倒顺序。第五行还有一个附加的键值对。

INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"foo\": \"bar\", \"color\": \"red\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"color\": \"blue\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"color\": \"green\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"foo\": \"bar\", \"color\": \"red\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"foo\": \"bar\", \"color\": \"red\", \"baz\": 2}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"color\": \"red\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"color\": \"red\"}');
INSERT INTO `mydb`.`table1` (`json_col`) VALUES ('{\"color\": \"red\", \"foo\": \"bar\"}');

现在通过使用以下查询:

SELECT 
json_col, 
json_col = JSON_OBJECT('foo', 'bar', 'color', 'red'), 
json_col = JSON_OBJECT('color', 'red', 'foo', 'bar') 
FROM table1;

我们得到:

{"foo": "bar", "color": "red"}  1   1
{"color": "blue"}   0   0
{"color": "green"}  0   0
{"foo": "bar", "color": "red"}  1   1
{"baz": 2, "foo": "bar", "color": "red"}    0   0
{"color": "red"}    0   0
{"color": "red"}    0   0
{"foo": "bar", "color": "red"}  1   1

请注意,json对象中的顺序也不重要。但是,其他键很重要。