1

我使用视图作为表来连接 3 个表上的数据:

create view category_list as 
select forum_categories.*, max( forum_answer.a_id ) as latest_answer_id 
from forum_categories 
left join forum_question on forum_question.catid = forum_categories.id 
left join forum_answer on forum_answer.question_id = forum_question.id
and forum_answer.qtitle = forum_question.topic;

但是,我遇到了两个问题:

  • 仅从 forum_categories 中提取一条记录进行链接
  • 我无法将 forum_answer.qtitle 与 forum_question.topic 相关联

请指教 :)

谢谢。

4

1 回答 1

1

缺少 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 );
于 2009-08-16T23:42:09.310 回答