mysql连接采样

e3bfsja2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(261)

我有一张table clients 带列 id , name , company .
和table agreements 带列 id , client_id , number , created_at .
一对多的关系。
我的问题:

SELECT 
    a.name, 
    a.company,
    b.number,
    b.created_at
FROM clients a
    JOIN agreements b
        ON b.client_id = a.id
    WHERE a.id = '{$clientId}'

结果是:

array(2) {
   [0]=>
       array(4) {
           ["name"]=>
           string(10) "Alton Wood"
           ["company"]=>
           string(10) "My company"
           ["number"]=>
           string(10) "5435635678"
           ["created_at"]=>
           string(10) "2018-08-11"
       }
   [1]=>
      array(4) {
          ["name"]=>
          string(10) "Alton Wood"
          ["company"]=>
          string(10) "My company"
          ["number"]=>
          string(10) "1234545546"
          ["created_at"]=>
          string(10) "2018-08-16"
    }
}

如何更改查询以获得输出?

array(1) {
   [0]=>
       array(3) {
           ["name"]=>
           string(10) "Alton Wood"
           ["company"]=>
           string(10) "My company"
           ["agreements"]=>
               array(2) {
                   [0]=>
                       ["number"]=>
                       string(10) "5435635678"
                       ["created_at"]=>
                       string(10) "2018-08-11"
                   }
                   [1]=>
                       ["number"]=>
                       string(10) "1234545546"
                       ["created_at"]=>
                       string(10) "2018-08-16"
                   }
               }
           }
       }
   }
}
kuuvgm7e

kuuvgm7e1#

我还没有测试过这个查询,因为我没有一个示例数据(如果你发布它,它会很有帮助:),但是类似的东西可能会起作用。

SELECT 
    a.name, 
    a.company,
    JSON_ARRAYAGG(JSON_OBJECT('number', b.number, 'created_at', b.created_at)) AS agreements
FROM clients a
JOIN agreements b
ON b.client_id = a.id
WHERE a.id = '{$clientId}'
GROUP BY 1,2

编辑:如果你想要答案作为数组,你可以使用

SELECT 
    a.name, 
    a.company,
    JSON_ARRAYAGG(JSON_ARRAY(b.number, b.created_at)) AS agreements
FROM clients a
JOIN agreements b
ON b.client_id = a.id
WHERE a.id = '{$clientId}'
GROUP BY 1,2

但在这种情况下,你会丢失钥匙。
希望有帮助

相关问题