【问题标题】:How can I use join in SQL to delete record?如何在 SQL 中使用 join 删除记录?
【发布时间】:2019-08-14 05:48:07
【问题描述】:

我的程序有问题我正在尝试使用 Java 连接从表中删除记录这是我的代码:

try{
            String sql ="DELETE f FROM facture f INNER JOIN client c ON f.idClient=c.id WHERE c.nom= ? ORDER BY idFact DESC LIMIT 1";
            PreparedStatement pr = conn.prepareStatement(sql);
            pr.setString(1,nom);
            pr.executeUpdate();
            System.out.println("supprimer");
        }catch (SQLException e){
            e.printStackTrace();
        }

这是错误:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY idFact DESC LIMIT 1' at line 1.

【问题讨论】:

    标签: java mysql sql jdbc mariadb


    【解决方案1】:

    在 MySQL/MariaDB 中,您可以选择:

    • 您可以使用ORDER BYLIMIT,而FROM 只能引用一张表。
    • 您可以有一个引用多个表的FROM

    解决方案?改写查询:

    DELETE FROM facture f 
        WHERE EXISTS (SELECT 1
                      FROM client c 
                      WHERE f.idClient = c.id AND c.nom = ? 
                     )
        ORDER BY f.idFact DESC
        LIMIT 1;
    

    或者您可以使用子查询来获取要删除的行:

    DELETE f
        FROM facture f JOIN
             (SELECT f.idFact
              FROM facture f JOIN
                   client c
                   ON f.idClient = c.id AND c.nom = ?
              ORDER BY f.idFact DESC
              LIMIT 1
             ) ff
             ON ff.idFact = f.idFact
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      相关资源
      最近更新 更多