如何在我的情况下最小化SQL?

时间:2015-04-02 03:51:12

标签: sql oracle

所以这是我的SQL -

select t.form_id, 
       t.created, 
       ui.first_name || ui.last_name as "created by name", 
       t.updated, 
       ui2.first_name || ui2.last_name as "updated by name"
from module_transport t
join user_info ui on ui.id = t.entered_by 
join user_info ui2 on ui2.id = t.last_updated_by
join client c on c.id = t.individual_id and lower(c.first_name) = 'gvznsbuv' and lower(c.last_name) = 'elpveol'
join company_info p on p.id = t.prov_id and p.code = 'AGB-02'
where to_char(t.created, 'MON-YYYY') = 'MAR-2014'
union all
select f.form_id, 
       f.created, 
       ui.first_name || ui.last_name as "created by name", 
       f.updated, 
       ui2.first_name || ui2.last_name as "updated by name"
from module_food f
join user_info ui on ui.id = f.created_by 
join user_info ui2 on ui2.id = f.last_updated_by
join client c on c.id = f.client and lower(c.first_name) = 'gvznsbuv' and lower(c.last_name) = 'elpveol'
join company_info p on p.id = f.prov_id and p.code = 'AGB-02'
where to_char(f.created, 'MON-YYYY') = 'MAR-2014';

这里,由'union all'子句连接的两个部分具有相同的逻辑。有没有办法在一个地方编写逻辑来应用这两个部分? 那么,效率会有多高?

1 个答案:

答案 0 :(得分:1)

您可以使用Oracle中的' WITH' 子句来简化查询。在您的查询示例中,可以使用带有别名的With子句来子化Company_Info表和Client表,并在join语句中引用别名。

有关WITH子句的更多信息,请参阅此link

示例SQL with' WITH'条款

  WITH dept_count AS (
    SELECT deptno, COUNT(*) AS dept_count
    FROM   emp
  GROUP BY deptno)
  SELECT e.ename AS employee_name,
     dc.dept_count AS emp_dept_count
  FROM   emp e,
     dept_count dc
  WHERE  e.deptno = dc.deptno;

使用这种方式可以简化您的逻辑,还可以加快查询性能。