簡體   English   中英

更新查詢在 MySQL 工作台中工作但不在 Java 代碼中工作

[英]Update Query working in MySQL workbench but not in Java code

我創建了一個查詢,我想在同一個表中使用內部查詢更新某些列。 並且查詢在 MySQL 工作台中工作正常,但是如果我在 java 中使用相同的查詢,那么它會給我類似的錯誤

expecting "set", found 'INNER'

這是我創建的查詢。

UPDATE table1 t1  
INNER JOIN (SELECT MAX(time)  
            FROM table1 WHERE id = 1) t2  
  ON t1.time = t2.time 
SET t1.fromUserId=305, 
    t1.toUserId=306,
    t1.type='Positive', 
    t1.subcategoryId=508, 
    t1.isDeleted=false,
    t1.isNotify=true;

Java代碼

   @Override
    public void methodName(DTOClass dtoClass) throws DatabaseException {
        logger.info("*******************In save-update ******************");
        StringBuilder saveQuery = new StringBuilder();
        try {
            saveQuery.append(" UPDATE table1 t1    INNER JOIN (SELECT MAX(time)  FROM table1 ");
            saveQuery.append(" WHERE id = :addedBy) t2  ON t1.time = t2.time ");
            saveQuery.append(" SET t1.fromUserId=:fromUserId, t1.toUserId=:toUserId, t1.type=:type, ");
            saveQuery.append( " t1.subcategoryId=:subcategoryId, t1.isDeleted=false, t1.isNotify=:isNotify ");
            logger.info(saveQuery.toString());
            Query query = getCurrentSession().createQuery(saveQuery.toString());
            query.setParameter("addedBy", dtoClass.getAddedBy());
            query.setParameter("fromUserId", dtoClass.getFromUserId());
            query.setParameter("toUserId", dtoClass.getToUserId());
            query.setParameter("type", dtoClass.getType());
            query.setParameter("subcategoryId", dtoClass.getSubcategoryId());
            query.setParameter("isNotify", dtoClass.getIsNotify());

            query.executeUpdate();

        } catch (Exception exception) {
            logger.error(exception.getMessage(), exception);
            throw new DatabaseException(ResourceManager.getProperty(EXCEPTION_DAO_USER));

        }

    }

有人可以幫忙嗎。 提前致謝!

從你的代碼getCurrentSession().createQuery(saveQuery.toString()); 我猜你正在使用一些 JPA 實現(spring 什么的?並且加入更新在 JPQL 中不可用( https://docs.oracle.com/javaee/6/tutorial/doc/bnbtl.html#bnbud

因此,您可以嘗試將其作為本機 mysql 查詢發送。 我不確定這樣做的確切方法是什么,因為我現在沒有這樣的項目,但我相信它是這樣的: getCurrentSession().createNativeQuery(saveQuery.toString()); 那么它應該可以工作,但它有點違背使用 JPA 的目的:)

所以我想你應該像上面提出的那樣重新處理查詢:

update table1 set fromUserId=305, toUserId=306 where time = (SELECT MAX(time)  FROM table1 WHERE id = 1);

你能試試這個嗎:

update A
set A.fromUserId=305, 
    A.toUserId=306,
    A.type='Positive', 
    A.subcategoryId=508, 
    A.isDeleted=false,
    A.isNotify=true
from table1  A
inner join (SELECT MAX(time) as bTime  FROM table1 WHERE id = 1) B
on (A.time = (B.bTime))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM