社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

MySQL 8.0的SQL查询JSON是字符串而不是数组

John • 4 年前 • 2139 次点击  

CREATE TABLE `airline_table` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`info` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

它包含JSON类型的数据,我插入一些数据如下:

INSERT INTO airline_table VALUES ('1','{"data": [{"city": "Houston", "state": "TX"}, 
      {"city": "Los Angles", "state": "CA"}], "airline": ["UA", "AA"]}');

我使用php访问数据库,希望得到“airline”作为数组的值。

<?php

$mysqli = new mysqli("localhost", "root", "aproot2019", "test");
$sql = "SELECT id, info -> '$.airline' AS airline FROM airline_table";

$result = $mysqli->query($sql);
$row = $result->fetch_array();
//print_r($row);
$airline = $row['airline'];

echo $airline . "<br>";   //  ["UA", "AA"] , this is a string but not an array, how can I have an Array? 
echo is_array($airline) ? 'Array' : 'not an Array'     . "<br>";      // not an Array
echo is_string($airline) ? 'String' : 'not a String'   . "<br>" ;    // String

$mysqli->close();

?>

但它是一个字符串,而不是数组! 这让我很恼火,MySQL中的JSON很难理解。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133560
文章 [ 2 ]  |  最新文章 4 年前
Luuk
Reply   •   1 楼
Luuk    4 年前

从MySQL查询JSON并不难,但是。。。。对于这种表,我不会使用JSON。

SELECT 
   j.city,
   j.state
FROM airline_table
CROSS JOIN JSON_TABLE(info, '$.data[*]' COLUMNS( 
       city VARCHAR(20) PATH '$.city', 
       state VARCHAR(20) PATH '$.state')) as j

输出:

城市 状态
休斯敦 德克萨斯州
洛杉矶 加利福尼亚州
Manish Kumar
Reply   •   2 楼
Manish Kumar    4 年前

你考虑过解码JSON吗?

$json = json_decode('{"data": [{"city": "Houston", "state": "TX"}, {"city": "Los Angles", "state": "CA"}], "airline": ["UA", "AA"]}');

// for your case it will be :
// $json = json_decode($row['airline']);
echo var_dump($json->airline);
/**
 * array(2) {
  [0]=>
  string(2) "UA"
  [1]=>
  string(2) "AA"
}