创建 SQL 个索引?

Creating SQL Indexes?

我的数据库中有两个表,大致如下所示:

通讯:(拨打电话)

Timestamp            FromIDNumber ToIDNumber GeneralLocation 
2012-03-02 09:02:30  878          674        Grasslands 
2012-03-02 11:30:01  456          213        Tundra 
2012-03-02 07:02:12  789          654        Mountains 

运动:

Timestamp            IDNumber Type        X   Y  
2012-03-02 11:02:30  379      pedestrian  32  46
2012-03-01 12:32:41  654      pedestrian  54  56
2012-03-02 07:02:16  789      pedestrian  39  52 

我想 运行 这个查询:

SELECT c.senderID, c.timestamp, m.timestamp, m.x, m.y
FROM communication c
JOIN movement m 
ON c.senderID = m.visitorID
WHERE m.timestamp >= c.timestamp
ORDER BY m.timestamp LIMIT 1;  

基本上,我想找到最接近给定通信时间戳的移动时间戳。

问题是,这些表有数百万个条目,我需要使用索引。问题是,我是 SQL 的新手,我不确定如何构建我的索引....我是否需要分别为 m.timestamp 和 c.timestamp 创建一个索引像这样?

CREATE INDEX mtstamp ON DBName.movement (timestamp); 

CREATE INDEX ctstamp ON DBName.communication (timestamp); 

任何帮助将不胜感激,谢谢!!

我会在 timestamp 和 table 上创建一个索引,因为该列在 WHERE 条件中用于筛选行以及在 ORDER BY 中用于排序.

此外,在 Communication table 中的 senderIDMovement table 中的 visitorID 上创建索引,除非它们是主键列在各自的 table 上;因为这两列涉及连接条件。

我认为您需要一个包含您在 JOIN 中使用的 ID 和时间戳的复合索引。否则,它将只使用 ID 索引进行连接,但随后必须扫描所有匹配的行以进行时间戳比较。

CREATE INDEX sender_timestamp ON communication (senderID, timestamp);
CREATE INDEX visitor_timestamp ON movement (visitorID, timestamp);