需要多个查询,每个查询需要结果

时间:2016-08-25 20:24:10

标签: sql postgresql sqlite

让我们说我有两个dbs,结构如下:

ID            CLASS          STUDENT_COUNT
1             Math              0
2             Biology           2
3             Algebra           1
4             Literature        5

ID            CLASS_ID          NAME
1             1                 Ted
2             1                 Mark
3             3                 Sally
4             4                 Sam

我正在尝试为getClassById(int id)编写一个查询,该查询将返回一个带有Class变量和List变量的对象。到目前为止,我能想到的唯一方法是使用2个查询。第一个会像这样查询:

select id, class, student_count from t_classes where id = an_id;

这将返回足够的信息来填充Class变量。然后,我需要在学生表上进行第二次查询才能填充列表:

select id, name from t_students where class_id = an_id

请原谅我极端的SQL新闻,但还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

此查询将为每位学生提供一行:

select c.id, c.class, c.student_count, s.id, s.name 
  from t_classes c
  join t_students s on s.class_id = c.id
 where c.id = an_id;

现在让我们以不同于其他方式想要结果集。

相关问题