我有这个HQL查询,它返回表中的所有产品。但我想只获得最新价格日期的产品,而不是旧产品。我怎么能这样做。
String select = "SELECT p FROM ProductPricing p where p.productId.supplierId.id=:id"; // nested condition based on the FK productpricing -> product -> supplier
Query query = hibernateSession.createQuery(select);
query.setParameter("id", Integer.parseInt(dsRequest.getFieldValue("supplier").toString()));
List<ProductPricing> models = query.list();
for (int i = 0; i < models.size(); i++)
{
if (models.get(i).getProductId() != null)
{
models.get(i).getProductId().getProductCode();
models.get(i).getProductId().getBrandName();
models.get(i).getPurchasePrice();
System.out.println(models.get(i).getProductId().getBrandName());
}
}
我的ProductPrice表格如下所示。现在这个我的HQL查询返回所有记录。但我只是想让它返回最新的价格日期,即那些productID的id 2和4
id priceDate purchasePrice salesPrice consumerPrice productID description
1 2012-11-15 00:00:00 1000 1200 1500 1 qwqw
2 2013-11-16 00:00:00 1600 1800 2100 1 new price
3 2012-10-15 00:00:00 1600 1500 1600 2 erere
4 2013-11-02 00:00:00 1600 1900 3400 2 new price
答案 0 :(得分:0)
这是返回最后30个日期定价
String select = "SELECT p.salesPrice FROM ProductPricing p where p.productId.supplierId.id=:id ORDER BY p.priceDate desc";
Query query = hibernateSession.createQuery(select);
query.setParameter("id", Integer.parseInt(dsRequest.getFieldValue("supplier").toString()));
List<ProductPricing> models = query.list();
在业务逻辑中过滤结果,我认为这就是你设计db的方式(一对多关系)
这是SQL:
CREATE TABLE `testspring`.`pricing`( `id` INT NOT NULL AUTO_INCREMENT , `priceDate` DATETIME , `purchasePrice` INT , `salesPrice` INT , `consumerPrice` INT , `productID` INT , `description` VARCHAR(255) , PRIMARY KEY (`id`) );
INSERT INTO `testspring`.`pricing`(`id`,`priceDate`,`purchasePrice`,`salesPrice`,`consumerPrice`,`productID`,`description`) VALUES ( NULL,'2012-11-15 00:00:00','1000','1200','1500','1','qwqw');
INSERT INTO `testspring`.`pricing`(`id`,`priceDate`,`purchasePrice`,`salesPrice`,`consumerPrice`,`productID`,`description`) VALUES ( NULL,'2013-11-16 00:00:00',1500,1600,1500,1,'new price');
INSERT INTO `testspring`.`pricing`(`id`,`priceDate`,`purchasePrice`,`salesPrice`,`consumerPrice`,`productID`,`description`) VALUES ( NULL,'2012-10-15 00:00:00','1600','1500','1600','2','qwqw');
INSERT INTO `testspring`.`pricing`(`id`,`priceDate`,`purchasePrice`,`salesPrice`,`consumerPrice`,`productID`,`description`) VALUES ( NULL,'2013-11-02 00:00:00','1600','1900','3400','2','new price');
SELECT p.salesPrice FROM pricing p INNER JOIN pricing pp ON p.productID = pp.productID AND p.priceDate>pp.priceDate
WHERE p.description<>pp.description
答案 1 :(得分:0)
您可以尝试这样:
String select = "SELECT p FROM ProductPricing p where p.productId.supplierId.id=:id and p.priceDate = NOW()";
Query query = hibernateSession.createQuery(select);
query.setParameter("id", Integer.parseInt(dsRequest.getFieldValue("supplier").toString()));
List<ProductPricing> models = query.list();