我创建了一个查询,我想在同一个表中使用内部查询更新某些列。并且查询在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));
}
}
有人可以帮忙。 提前谢谢!
答案 0 :(得分:1)
从你的代码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);
答案 1 :(得分:0)
你可以试试这个:
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))