2012-06-06 64 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