如何从外键 table 中检索值?

How to retrieve values from Foreign Key table?

我正在尝试获取外键每列的值 table。所以我使用 第二范式 将我的 table 归一化,我将 table 分成两部分。下图。

第一个 Table 我的主键是 SECTION_ID 在第二个 Table.

中引用 SECTION_ID

我在这里提供 SECTION_NAME 的值以搜索记录是否存在。如果用户输入现有记录我想做什么 我想获取外键 table 的所有值。我将如何做?

代码

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String searchSection = Section_SearchSection_Textfield.getText();
    String searchStudentLimit = Section_Student_Limit_ComboBox.getSelectedItem().toString();

    String searchSECTION_NAME = "SELECT * FROM allsections_list WHERE SECTION_NAME = ?";

    try (Connection myConn = DBUtil.connect();
             PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTION_NAME);)
        {
             myFirstPs.setString(1, searchSection);

             try (ResultSet myRs = myFirstPs.executeQuery())
             {
                 int resultCounter = 0;
                 while (myRs.next())
                 {
                     String mySectionName = myRs.getString(2);//Get the value of SECTION_NAME
                     Section_SectionName_TextField.setText(mySectionName);
                     Section_SectionName_TextField.setEnabled(true);
                     resultCounter++;
                 }
                 if (resultCounter == 1)//If exist
                 {
                     JOptionPane.showMessageDialog(null, "Data Found");
                 }
                 else//If not exist
                     JOptionPane.showMessageDialog(null, "No Data Found");
             }}

我是否需要为外键创建另一个 select 查询?我认为不是,因为我只是想获得价值。如果我错了纠正我。请随时发表评论。谢谢! :)

LEFT JOIN 关键字 returns 从左边开始的所有行 table (table1),匹配行在右边 table (table2).没有匹配时结果右侧为NULL

勾选这个SQL Left JOIN

使用select * from allsections_list A left outer join allsections_settings S on A.Section_ID = S.Section_ID并获取您需要的值