一句SQL的优化?-----在线等待
具体功能是指带3个参数的sql查询语句,
1,开始时间(fromdate)不为空则应该大于该时间
2,结束时间(todate)不为空则应该小于该时间
3,工作组(workclass)为空选出所有的组
三者都可能为空的。
问题有没有更简单的SQL,应该怎么优化?
SELECT *
FROM DR_GROUP_CONFIG
WHERE
(:fromdate IS NOT NULL) AND (:todate IS NOT NULL) AND (:workclass IS NOT NULL) AND (FROM_DATE > = :fromdate) AND (TO_DATE <= :todate) AND (WORK_CLASS = :workclass)
OR (:fromdate IS NOT NULL) AND (:todate IS NULL) AND (:workclass IS NOT NULL) AND (FROM_DATE > = :fromdate) AND (WORK_CLASS = :workclass)
OR (:fromdate IS NULL) AND (:todate IS NOT NULL) AND (:workclass IS NOT NULL) AND (TO_DATE <= :todate) AND (WORK_CLASS = :workclass)
OR (:fromdate IS NULL) AND (:todate IS NULL) AND (:workclass IS NOT NULL) AND (WORK_CLASS = :workclass)
OR (:fromdate IS NOT NULL) AND (:todate IS NOT NULL) AND (:workclass IS NULL) AND (FROM_DATE > = :fromdate) AND (TO_DATE <= :todate)
OR (:fromdate IS NOT NULL) AND (:todate IS NULL) AND (:workclass IS NULL) AND (FROM_DATE > = :fromdate)
OR (:fromdate IS NULL) AND (:todate IS NOT NULL) AND (:workclass IS NULL) AND (TO_DATE <= :todate)
OR (:fromdate IS NULL) AND (:todate IS NULL) AND (:workclass IS NULL) AND (1 = 1)
ORDER BY FROM_DATE
FROM后面的语句,有没有可以优化的?
------解决方案--------------------先判断3个值,再组合sql语句,好一点吧,直接写太累了
------解决方案--------------------SELECT *
FROM DR_GROUP_CONFIG
WHERE 1=1
if .....
if .....
------解决方案--------------------MERGE INTO DR_GROUP_CONFIG t1
using (SELECT nvl(:fromdate, '19010101 ') begin_date,nvl(:todate end_date, '20991231 '),
:workclass workclass FROM dual) t2
on (t1.FROM_DATE> =t2.begin_date and t2.workclass is null
)
when matched then
select * from DR_GROUP_CONFIG;
WHEN NOT MATCHED THEN
MERGE INTO DR_GROUP_CONFIG t1
using (SELECT nvl(:fromdate, '19010101 ') begin_date,nvl(:todate end_date, '20991231 '),
:workclass workclass FROM dual) t2
on (t1.FROM_DATE> =t2.begin_date and t2.workclass is not null
)
when matched then
select * from DR_GROUP_CONFIG t where t.WORK_CLASS=t2.workclass;
------解决方案--------------------忘了,把FROM_DATE和to_date加个to_char()