我是sql索引的新手,并且希望对此进行索引
CREATE TABLE IF NOT EXISTS message (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
remoteId TEXT,
text TEXT,
timestamp INTEGER NOT NULL DEFAULT 0,
channelId TEXT NOT NULL,
accountId TEXT NOT NULL,
username TEXT NOT NULL,
editUsername TEXT,
wm_createdUsername TEXT,
wm_organizedUsername TEXT,
rc_username TEXT,
p_messageRemoteId TEXT,
c_messageRemoteId TEXT,
....
UNIQUE (remoteId, accountId),
FOREIGN KEY (channelId, accountId) REFERENCES channel(id, accountId) ON DELETE CASCADE,
FOREIGN KEY (p_messageRemoteId, accountId) REFERENCES message(remoteId, accountId) ON DELETE CASCADE,
FOREIGN KEY (c_messageRemoteId, accountId) REFERENCES message(remoteId, accountId) ON DELETE CASCADE
);
CREATE VIEW messageAndUser AS
SELECT ...
FROM message
LEFT JOIN user AS u ON message.username = u.name AND message.accountId = u.accountId
LEFT JOIN user AS e ON message.editUsername = e.name AND message.accountId = e.accountId
LEFT JOIN user AS wm ON message.wm_organizedUsername = wm.name AND message.accountId = wm.accountId
LEFT JOIN user AS rc ON message.rc_username = rc.name AND message.accountId = rc.accountId
LEFT JOIN user AS i ON message.i_username = i.name AND message.accountId = i.accountId;
channelMessages:
SELECT *
FROM messageAndUser
WHERE channelId=? AND accountId=?
ORDER BY timestamp DESC
;
我的直觉告诉我,索引需要作为一个单元放在AND语句的所有部分。
但是,我不确定该怎么做,如果我有一个覆盖视图中所有联接部分的索引,现在如果该视图中的查询(即select from view where foo=?
)是否需要创建新的索引包含视图+ foo的索引中的所有列?还是有办法构成这个?
答案 0 :(得分:0)
视图无法直接建立索引,但可以受益于视图查询所涉及的表中存在的索引。
查看您的架构和视图,您似乎错过了要加入的主要索引
table message column accountId
做一个事实,即唯一索引UNIQUE(remoteId,accountId在右侧显示了accountId。.这对于在视图..中使用的联接没有用。