嵌套在java中选择

时间:2018-04-29 04:28:18

标签: java sql

我想将下面代码中的2个选项合并到具有嵌套选择的单个查询中。我怎样才能做到这一点?

这是我的代码

  int idst1 = // some Integer value

  String SQLST1 = "select idl from " +
                  "studentlesson " +
                  "WHERE id=" + idst1;

  rs = stmt.executeQuery(SQLST1);
  rs.first();
  id1 = rs.getInt(1);

  String curses = "SELECT namel FROM lesson where idl=" + id1;
  rs = stmt1.executeQuery(curses);
  rs.first();

  System.out.println("nxt:" + rs.next());
  String s = rs.getString(7);
  System.out.println(idst1 + ", " + s + ", ");

1 个答案:

答案 0 :(得分:1)

假设我得到了正确的答案,你的表格如下:

LESSON
------
name1
id1

STUDENTLESSON
-------------
id
id1

其中LESSON.id1STUDENTLESSON.id1

相同

您可以使用以下查询:

SELECT name1 FROM LESSON, STUDENTLESSON
WHERE LESSON.id1 = STUDENTLESSON.id1
AND STUDENTLESSON.id = idst1

或写为正确的JOIN:

SELECT LESSON.name1
FROM LESSON
INNER JOIN STUDENTLESSON ON LESSON.id1=STUDENTLESSON.id1
WHERE id1 = idst1;