2015-04-02 47 views
0

所以這是我的SQL -如何在我的情況下最小化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」加盟條款兩個部分具有相同的邏輯。有沒有什麼方法可以將邏輯寫在一個地方,這將適用於這兩個部分? 另外,這將是多高效?

+0

你爲什麼選擇sql-server標籤? – cha 2015-04-02 03:54:44

+0

因爲這個SQL對於Oracle和MSSQL用戶都應該很熟悉。所以,這個問題可能會得到任何平臺用戶的回答。 – 2015-04-02 03:58:20

+0

是的,它可能是,但你也可能得到一個根本不起作用的答案 - 因此,浪費人們回答問題的時間 – 2015-04-02 04:07:05

回答

1

您可以使用Oracle中的'WITH'子句來簡化查詢。在您的查詢示例中,Company_Info表和Client表可以使用具有別名的With子句進行子查詢並在聯接語句中引用別名。

有關WITH子句的更多信息,請參閱此link

例如,SQL與「用」條款

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; 

使用這種方式可以簡化你的邏輯,也可以繫緊你的查詢性能。

相關問題