我使用sqlite数据库处理我的项目。在项目中有一个聊天,没有频道,只有1对1.这些是表格:
db.run(`CREATE TABLE IF NOT EXISTS user (
id integer PRIMARY KEY AUTOINCREMENT,
firstName varchar(30),
lastName varchar(50),
email varchar(150),
phone varchar(12),
address varchar(255),
photo varchar(255),
hash varchar(255),
token varchar(255)
)`);
db.run(`CREATE TABLE IF NOT EXISTS chat (
id integer PRIMARY KEY AUTOINCREMENT,
lastMessage varchar(255)
)`);
db.run(`CREATE TABLE IF NOT EXISTS chatUser (
id integer PRIMARY KEY AUTOINCREMENT,
idChat integer,
idUser integer,
FOREIGN KEY (idChat) REFERENCES chat(id) ON DELETE CASCADE,
FOREIGN KEY (idUser) REFERENCES user(id) ON DELETE CASCADE
)`);
db.run(`CREATE TABLE IF NOT EXISTS message (
id integer PRIMARY KEY AUTOINCREMENT,
idChat integer,
idUser integer,
text varchar(255),
FOREIGN KEY (idChat) REFERENCES chat(id) ON DELETE CASCADE,
FOREIGN KEY (idUser) REFERENCES user(id) ON DELETE CASCADE
)`);
在chatUser
表中,我总是只添加两个用户(当前用户和重写它的用户)。我正在尝试进行查询以获取当前用户聊天的列表(列表应包括与我聊天和最后留言的人的姓名,照片,聊天ID)
db.all(`
SELECT chatUser.idChat,
user.firstName,
user.lastName,
user.photo,
chat.lastMessage
FROM user, chatUser, chat
WHERE user.id = chatUser.idUser
AND chat.id = chatUser.idChat
AND user.id != ?
`, [id], function(error, chats) {
...
}
id - 当前用户ID 的位置。这工作直到我来自另一个用户,而不是一个聊天,显示两个额外的用户。请帮我正确构建查询。
答案 0 :(得分:0)
您可以想象查询分为两个步骤:
当前用户的贝娄示例等于1:
SELECT othersChatUser.idChat,
user.firstName,
user.lastName,
user.photo,
chat.lastMessage
FROM
user,
chatUser as currentChatUser,
chatUser as othersChatUser,
chat
WHERE currentChatUser.idUser = 1
AND currentChatUser.idChat = othersChatUser.idChat
AND user.id = othersChatUser.idUser
AND user.id <> currentChatUser.idUser
AND chat.id = othersChatUser.idChat;
您的查询结果:SQL Fiddle