如何在SQL中使用Join删除记录?

时间:2019-03-23 11:22:52

标签: java mysql sql jdbc mariadb

我的程序出现问题,我正在尝试使用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.

1 个答案:

答案 0 :(得分: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