在没有json的情况下,数据库很难把不同结构的数据一次性返回,如果你很在乎查询次数,可以参考一下。
现在mysql和postgresql都支持json了,这边我以postgresql为例,写个例子:
假设我们有数据表t1,有两列:name,version,我们统计name为aaa和bbb的数量,同时返回整个t1的数据
select row_to_json(t)
from (
select (select count(*) from test.t1 where name='aaa') as aaa_count,
(select count(*) from test.t1 where name='bbb') as bbb_count,
(
select array_to_json(array_agg(row_to_json(d)))
from (
select name, version
from test.t1
) d
) as names
) as t
说明:
row_to_json可以把表查询结果转成json
array_to_json可以把数组转成json
通过array_agg可以把多条row_to_json的结果转成数组
查询结果为:
{
"aaa_count":1,
"bbb_count":1,
"