SELECT .. IN(..)的替代方案

时间:2011-03-19 05:50:37

标签: sql select subquery sql-subselect

我有3列的表:id(人),城市(访问者)和日期(访问)。 我需要选择在特定日期之间在洛杉矶市的所有人(他们的ids),他们也在其他特定日期在纽约市。

以下是我现在运行的查询示例:

SELECT DISTINCT id 
FROM places 
WHERE date >= '2011-03-18' AND 
      date < '2011-03-19' AND 
      city = 'los angeles' AND 
      id IN (SELECT DISTINCT id 
             FROM places 
             WHERE date >= '2011-03-15' AND 
                   date < '2011-03-16' AND 
                   city = 'chicago' 
             GROUP BY id);

我还可以吗? 我可以使用其他任何查询吗?这个选择太慢了。

4 个答案:

答案 0 :(得分:8)

使用连接(带别名)而不是子查询应该更好:

  SELECT places.id 
    FROM places 
         JOIN places AS places2 ON places2.id = places.id
     AND places2.date >= '2011-03-15' 
     AND places2.date < '2011-03-16' 
     AND places2.city = 'chicago' 
   WHERE places.date >= '2011-03-18' 
     AND places.date < '2011-03-19' 
     AND places.city = 'los angeles' 
GROUP BY places.id;

答案 1 :(得分:2)

首先,您需要确保具有相关的索引。在这种情况下,它可能是一个具有两列日期和城市的索引。之后,您可以查询并将性能与此处建议的查询进行比较。内连接可能比你已经获得的更快。

我的版本适用于SQL Server。我也可以在其他DBMS中工作。

select id 
from places 
where [date] >= '2011-03-18' AND 
      [date] < '2011-03-19' AND 
      city = 'los angeles'
intersect       
select id 
from places 
where [date] >= '2011-03-15' AND 
      [date] < '2011-03-16' AND 
      city = 'chicago';

答案 2 :(得分:1)

SELECT id
FROM places AS p1
INNER JOIN AS p2 ON p1.id = p2.id AND p2.date >= '2011-03-15' AND p2.date < '2011-03-19'
   AND p2.city = 'chicago'
WHERE p1.date >= '2011-03-18' AND p1.date < '2011-03-19' AND p1.city = 'los angelis'

答案 3 :(得分:1)

尝试内连接

SELECT DISTINCT p1.id 
FROM places p1
INNER JOIN places p2 ON p1.id = p2.id AND
      p2.date >= '2011-03-18' AND 
      p2.date < '2011-03-19' AND 
      p2.city = 'los angeles'
WHERE p1.date >= '2011-03-18' AND 
      p1.date < '2011-03-19' AND 
      p1.city = 'los angeles' AND 

检查表格上的索引,看看你是否有城市和日期。