【问题标题】:Insert a row in a table with referencing to a value from other table在表中插入一行并引用其他表中的值
【发布时间】:2021-10-03 16:57:25
【问题描述】:

我有 2 个表,分别是 subjectstudent

 id |            name
----+-----------------------------
  1 | Math

id | student_name | score | subject_id
----+--------------+-------+------------
 11 | Mark         |  78.5 |          2

我有 Java 代码

public boolean insertStudent(String student_name,float score,String name) {
        boolean res=false;
        try(PreparedStatement statement=this.c.prepareStatement(INSERT_STU);){
            statement.setString(1,student_name);
            statement.setFloat(2,score);
            statement.setString(3,name);
            res=statement.execute();
            
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return res;
    }

我有 INSERT_STU 的查询字符串

private static final String INSERT_STU="INSERT INTO student(student_name,score,subject_id) VALUES(?,?,(SELECT id from subject where name=?))";

这在 postgres 中有效。但是还有其他方法吗? *它必须与主题名称(字符串名称)一起传递,而不是主题 ID。由于我不知道 subject_id,所以我传递了名称。

【问题讨论】:

  • 顺便说一句……所以一个学生只能分配一个科目和分数?我怀疑您的数据模型不正确。您可能有需要第三个桥接表的多对多关系。
  • 如果您知道主题 ID,为什么不直接插入?你的问题到底是什么?
  • @BasilBourque 现在,我只是在学生只有一门学科的情况下学习这个。我只是想知道是否还有其他方法可以使用内部连接编写 INSERT 查询?

标签: java mysql sql postgresql


【解决方案1】:

您可以将您的查询更改为可能更具可读性的查询:

INSERT INTO student (student_name,score,subject_id) 
SELECT ?,?,id from subject where name = ?

但这里要小心,如果我们在主题表中找不到给定名称的任何匹配项,则不会插入任何内容。

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 2013-04-22
    • 1970-01-01
    • 2011-06-11
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    相关资源
    最近更新 更多