【问题标题】:How to run a MySQL query for all rows having column json value with key pair?如何对具有键值对的列 json 值的所有行运行 MySQL 查询?
【发布时间】:2023-01-20 15:43:31
【问题描述】:

我有一个表,其中一列包含 json 值。现在我想根据特定条件对该列的键值运行查询。谁能帮忙?

现在从上表中我想运行一个查询:我想获取名字为“test”或姓氏为“test”的记录。谁能帮忙?

我试过在 php 中使用子查询,但我不知道如何直接从 Mysql 查询中获取。

这是我在 PHP 中尝试过的:

桌子

 id    name                                       status
  1    {"firstname": "rohit", "lastname":"test"}    Y
  2    {"firstname": "test", "lastname":"test"}     Y
  3    {"firstname": "raj", "lastname":"malhotra"}  Y
$sql=$query->("select * from table order by RAND() DESC limit 1");
    if($sql->num_rows>0){
       while ($obj= fetch_object($sql)){
          $name=json_decode($obj->name, true);
          $firstname=$name['firstname'];
          $lastname=$name['lastname'];
           if(strpos($firstname, "test") !==false || strpos($lastname, "test") !==false){
           echo 'present';
           }
       }
    }

【问题讨论】:

标签: php mysql


【解决方案1】:

您可以使用两个运算符 ->->> 查询 JSON,如下所示:

-> 按原样返回值:

select id, 
       name->'$.firstname' as firstname,
       name->'$.lastname' as lastname
       from tableName;

->> 将输出返回为带引号的字符串:

select id, 
       name->>'$.firstname' as firstname,
       name->>'$.lastname' as lastname
       from tableName;

更多 details

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多