INSERT INTO ... VALUES ... SELECT。如何使用INSERT创建嵌套语句?

时间:2014-05-13 15:56:26

标签: java mysql jdbc

请告诉我如何对DB执行语句。 有2个表(抱歉写错了 - 只是提供有关列的信息):

  1. 承包商(contractor_id,contractor_name,contract_num)

  2. 发票(contractor_id,invoice_num,invoice_date,invoice_amount)

  3. ' contractor_id'在'发票'是' contractor_id'的外键。在'承包商'。如何在'发票中插入以下数据:invoice_num,invoice_date,invoice_amount,如果我有' contractor_name'来自承包商' -table?

    有效的解决方案是:

    public void insertInvoiceDataByContractorName(String contractorsName, String invoiceNum, String date, float amount) {
            String contrId = null;
            try {
                preparedStatement = connection.prepareStatement("SELECT contractor_id FROM contractors WHERE contractor_name=?");
                preparedStatement.setString(1, contractorsName);
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    contrId = resultSet.getString(1);
                }
                preparedStatement = connection.prepareStatement("INSERT INTO invoices VALUES(?, ?, ? ,?)");
                preparedStatement.setString(1, contrId);
                preparedStatement.setString(2, invoiceNum);
                preparedStatement.setString(3, date);
                preparedStatement.setFloat(4, amount);
                preparedStatement.execute();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (preparedStatement != null) {preparedStatement.close();}
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    

    我不知道如何只使用一个陈述使其更正确,更简单。提前感谢您的建议。

1 个答案:

答案 0 :(得分:3)

使用

INSERT INTO invoices SELECT contractor_id, ?, ?, ?  FROM contractors WHERE contractor_name=?

假设您的承包商名称是唯一的,这将插入1行