如何将两列值CONCAT转换为JSON格式?

时间:2019-01-14 07:25:37

标签: mysql concatenation

我想将CONCAT的两列值stringJSON格式转换为一个字符串。但是我在查询中的引号和双引号有问题。如何解决查询问题,使其成功产生预期结果?

$concat = "CONCAT('{"CODE":"pm_r.CODE","NAME":"pm_r.NAME"}') AS `JSON`"
$query  = $this->db->query(
    'SELECT pm_r.ID_REQUIREMENT, '.$concat.'FROM `pm_requirement` `pm_r`'
);

预期结果应该是:

ID_REQUIREMENT   JSON
ID001            {"CODE":"001","NAME":"Shane"}

1 个答案:

答案 0 :(得分:0)

为避免引用冲突,一种解决方案是使用php HEREDOC string

我还修复了CONCAT,要连接的列的名称应与字符串的固定部分分开。

$query  = $this->db->query(<<<EOT
    SELECT 
        pm_r.ID_REQUIREMENT,
        CONCAT('{"CODE":"', pm_r.CODE, '","NAME":"', pm_r.NAME, '"}') AS `JSON`
        FROM `pm_requirement` `pm_r`
EOT
);