想象一下下表(它有其他行,但下面显示的是在查询中使用的那些),
+-------------------+-----------------+---------------------+
| INTERVAL_QUANTITY | INTERVAL_UOM_ID | LAST_UPDATED_STAMP |
+-------------------+-----------------+---------------------+
| 10 | TF_wk | 2017-10-31 17:21:40 |
| 20 | TF_mon | 2017-10-30 17:21:40 |
| 30 | TF_day | 2017-10-29 17:21:40 |
+-------------------+-----------------+---------------------+
关键
现在,我有以下查询,
SELECT
*
FROM
product_maint
WHERE
( INTERVAL_UOM_ID = 'TF_day' OR INTERVAL_UOM_ID = 'TF_wk' OR INTERVAL_UOM_ID = 'TF_mon' )
AND DATEDIFF( DATE( DATE_ADD( LAST_UPDATED_STAMP, INTERVAL INTERVAL_QUANTITY DAY ) ), DATE( NOW( ) ) ) <= 0;
问题是,当它选择INTERVAL_UOM_ID
TF_wk
INTERVAL_QUANTITY
10
70
行时,实际需要在10
天内添加不是INTERVAL_UOM_ID
天,同样当TF_mon
为INTERVAL_QUANTITY
且20
为560
时需要在package helloworldexample;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HelloWorldExample {
private static SessionFactory factory;
private static ServiceRegistry registry;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String m = "";
System.out.println("Enter a message: ");
m = in.nextLine();
try{
Configuration conf = new Configuration().configure();
registry = new StandardServiceRegistryBuilder().applySettings(
conf.getProperties()).build();
factory = conf.buildSessionFactory(registry);
} catch (Throwable ex){
System.err.println("Failed to create session factory object"+ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
Short msgId = null;
try{
tx=session.beginTransaction();
Message msg = new Message(m);
msgId = (Short) session.save(msg);
List messages = session.createQuery("FROM Message").list();
for(Iterator iterator = messages.iterator(); iterator.hasNext();){
Message message = (Message)iterator.next();
System.out.println("message: "+message.getMessage());
}
tx.commit();
}catch(HibernateException e){
if(tx != null) tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
StandardServiceRegistryBuilder.destroy(registry);
}
}
天添加(假设我的所有数学是正确的。)
我将如何实施此逻辑?
答案 0 :(得分:1)
您需要分别检查每个间隔。我想你想要:
WHERE ( INTERVAL_UOM_ID = 'TF_day' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY DAY
) OR
( INTERVAL_UOM_ID = 'TF_wk' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY WEEK
) OR
( INTERVAL_UOM_ID = 'TF_mon' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY MONTH
)
请注意,我已将NOW()
更改为CURDATE()
。我不认为时间组件对你想做的事情很重要。另请注意,我将逻辑更改为仅使用日期算法。