1

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

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

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

4 回答 4

9

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

  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;
于 2011-03-19T05:57:34.047 回答
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'
于 2011-03-19T06:00:02.343 回答
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 

检查表上的索引,看看你有没有关于城市和日期的索引。

于 2011-03-19T06:04:36.700 回答
1

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

我的版本适用于 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';
于 2011-03-19T06:18:59.167 回答