【问题标题】:Fetch rows from postgres database from JSON datatype particular value从 JSON 数据类型特定值从 postgres 数据库中获取行
【发布时间】:2019-06-16 15:55:18
【问题描述】:

您好,我在从 Json 列中提取行时遇到问题。
下面是 json 数据,如果我想从值中提取行,请说 MH。

以下数据位于每一行中。所以我需要一个 codeigniter 查询,如果我查询这个适用性列的 MH 需要获取行。
你能帮我解决这个问题吗:

下面是JSON数据:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JK","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UT","UP","WB","AN","CH","DN","DD","DL","LD","PY"]

$this->select('guid, applicability, name, type, description,
        service_type, scheme_type, mini_description, tags, benefit');
        $this->join('schemes_lang_1', 'schemes_lang_1.scheme_id=scheme_1.id', 'left');
$this->where('lang', $lang);
$this->where('status', $status);
$this->where('scheme_1.pp_enabled', 1);
$this->where('scheme_1.applicability', 'MH');
return $this->findAll();

表结构如下。

【问题讨论】:

    标签: php mysql postgresql codeigniter


    【解决方案1】:

    访问以下网站

    访问http://www.postgresqltutorial.com/postgresql-json/

    然后从

    更改您的代码
    $this->select('guid, applicability, name, type, description,
    service_type, scheme_type, mini_description, tags, benefit');
    $this->join('schemes_lang_1', 'schemes_lang_1.scheme_id=scheme_1.id', 'left');
    $this->where('lang', $lang);
    $this->where('status', $status);
    $this->where('scheme_1.pp_enabled', 1);
    $this->where('scheme_1.applicability', 'MH');
    return $this->findAll();
    

    到

    $query = $this->db->query("YOUR POSTGRES QUERY");
    
    foreach ($query->result_array() as $row)
    {
      echo $row['guid'];
      echo $row['applicability'];
      echo $row['name'];
    }
    

    【讨论】:

    • 这并没有真正利用 SQL 和 postgresql jsonb 的好处。也应该避免循环
    【解决方案2】:

    下面给出的是行查询,您可以将此查询用作参考并添加所需的条件

    SELECT
      guid, 
      applicability, 
      name, 
      type, 
      description,
      service_type, 
      scheme_type, 
      mini_description, 
      tags, 
      benefit
    FROM scheme_1
    LEFT JOIN schemes_lang_1 ON schemes_lang_1.scheme_id=scheme_1.id
    WHERE
      (scheme_1.applicability)::jsonb ? 'MH';
    

    您也可以通过 json 键检查条件,例如 如果json是这样的

    ["company":"AP","Detail":"test"]
    

    使用(scheme_1.applicability->'company')::jsonb ? 'AP';

    在 Codeignitor 中你可以这样做

    $this->select('guid, applicability, name, type, description,
    service_type, scheme_type, mini_description, tags, benefit');
    $this->join('schemes_lang_1', 'schemes_lang_1.scheme_id=scheme_1.id', 'left');
    $this->where('lang', $lang);
    $this->where('status', $status);
    $this->where('scheme_1.pp_enabled', 1);
    $this->where('(scheme_1.applicability)::jsonb ? ', 'MH');
    
    return $this->findAll();
    

    注意:它比使用循环要快得多,然后在表字段中逐条搜索,循环搜索可能会使代码的时间和空间复杂度增加 1000 倍。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      相关资源
      最近更新 更多