【问题标题】:Retrive data which is save in json format using mysql Query (codeigniter)使用 mysql Query (codeigniter) 检索以 json 格式保存的数据
【发布时间】:2017-03-19 11:46:57
【问题描述】:

M 使用 json 格式将数据保存到数据库中,例如:

state_id city_id
["21"]   ["32,35,67"]

现在想使用 mysql 查询(codeigniter)where state_id = 21 AND city_id = 32 进行搜索。

谁能帮帮我,在谷歌搜索时我发现了一个东西“json_extract”,但它不知道如何在查询中使用它。

【问题讨论】:

标签: php mysql codeigniter


【解决方案1】:

如果我理解正确,这就是答案:

$json = '{"state_id": 21, "city_id": [32,35,67]}';
$decodedJson = json_decode($json, true);

/** @var $state_id int */
/** @var $city_id array */
extract($decodedJson);

$sql = printf("SELECT * FROM `table_name` WHERE `state_id` = %d AND `city_id` IN ( %s );", $state_id, join(',', $city_id));

echo $sql.PHP_EOL;

输出:

SELECT * FROM table_name WHERE state_id = 1 AND city_id IN (1,2,3);

【讨论】:

  • 好的,将尝试上面的代码并更新你...谢谢
【解决方案2】:

使用JSON_SEARCH

select * from `table` where JSON_SEARCH(`city_id`, 'all', '32') IS NOT NULL;

对于 codeigniter,只需使用查询功能 -因为我无法在 codeigniter 中找到另一个内置的探测器来执行此操作- :

$results = $this->db->query('select * from `table` where JSON_SEARCH(`city_id`, "all", "' . $city_id . '") IS NOT NULL;');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2018-05-18
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多