缺少 group by 子句。这是我放在一起的一个非常简单的例子,下面是我用来创建简单测试数据的sql。
select
cat.*
, max( ans.id )
from cat
left join ques on ques.cat_id = cat.id
left join ans on ans.ques_id = ques.id
group by cat.id, cat.name
create table cat ( id serial, name varchar (10) );
create table ques ( id serial, name varchar (10), cat_id integer );
create table ans ( id serial, name varchar (10), ques_id integer );
insert into cat (name) values ( 'cat 1' );
insert into cat (name) values ( 'cat 2' );
insert into cat (name) values ( 'cat 3' );
insert into ques (name, cat_id) values ( 'ques 1', 1 );
insert into ques (name, cat_id) values ( 'ques 2', 1 );
insert into ques (name, cat_id) values ( 'ques 3', 1 );
insert into ques (name, cat_id) values ( 'ques 4', 2 );
insert into ques (name, cat_id) values ( 'ques 5', 2 );
insert into ques (name, cat_id) values ( 'ques 6', 2 );
insert into ques (name, cat_id) values ( 'ques 7', 2 );
insert into ans (name, ques_id) values ( 'ans 1', 1 );
insert into ans (name, ques_id) values ( 'ans 2', 2 );
insert into ans (name, ques_id) values ( 'ans 3', 2 );
insert into ans (name, ques_id) values ( 'ans 4', 1 );
insert into ans (name, ques_id) values ( 'ans 5', 2 );
insert into ans (name, ques_id) values ( 'ans 6', 1 );
insert into ans (name, ques_id) values ( 'ans 7', 1 );
insert into ans (name, ques_id) values ( 'ans 8', 1 );
insert into ans (name, ques_id) values ( 'ans 9', 2 );
insert into ans (name, ques_id) values ( 'ans 10', 2 );