2012-06-06 63 views
1

我在數據庫中查詢數據,如下表具有的Oracle SQL查詢重寫

COLUMNS: Type, Location, name, etc. 

DATA: 
1. Stores in NJ, name = xyz 
2. Restaurants in NY 
3. Hotels in US 
4. Stores in PA 
5. Restaurants in VA 
6. Hotels in MD 
7. Stores in NJ, name = abc 
8. etc. 

我需要一個查詢,從1,2取數據,3

現在,我有以下查詢。這運行得更快。但是否有任何其他查詢,我可以使用,而不UNION

select type, location from table1 
where type='stores' and location='NJ' and name='XYZ' 
    UNION 
select type, location from table1 
where type='restaurants' and location='NY' 
    UNION 
select type, location from table1 
where type='hotels' and location='US' 
+0

不要在這種情況下使用'union'。它會嘗試做一個「獨特」的,這意味着你不必要的去重複。 – Ben

回答

2

您可以使用OR:

select type, location from table1 
where (type='stores' and location='NJ' and name='XYZ') 
or (type='restaurants' and location='NY') 
or (type='hotels' and location='US'); 
+0

感謝安德魯您的答案。我嘗試了這一點,與我以前的查詢相比,花費了相當長的時間。我的表格包含大量的數據。 – user12121

+0

你的表格是否有準確的(足夠的)統計數據? –

1

UNION ALL更快然後使用OR和prolly是你真正需要的:

select type, location from table1 
where type='stores' and location='NJ' and name='XYZ' 
    UNION ALL 
select type, location from table1 
where type='restaurants' and location='NY' 
    UNION ALL 
select type, location from table1 
where type='hotels' and location='US' 

如果您真的想要OR

select type, location from table1 
where (type='stores' and location='NJ' and name='XYZ') 
or (type='restaurants' and location='NY') 
or (type='hotels' and location='US'); 

爲了讓您更快的查詢,在typelocationname列創建索引!

+0

雅,嘗試OR,但我的查詢現在非常緩慢。有什麼我可以使用的,如標量子查詢等。如果是這樣,那麼語法是什麼。 – user12121

+0

爲了更快速地在類型,位置和名稱列上創建索引! –

+0

謝謝aF。我按照你的建議創建了索引。仍然沒有運氣。 – user12121