我想从数据库中的消息表中为单个用户提取消息,我写的查询有一些语法问题,但我不知道如何修复它。请帮忙
SELECT *
FROM Messages
WHERE SenderId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
or ReceiverId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
IN (SELECT * FROM Messages WHERE SenderId = 1 or ReceiverId = 1)
答案 0 :(得分:1)
它遗漏了什么
WHERE SenderId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
or ReceiverId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
<missing expression here> IN (SELECT * FROM Messages WHERE SenderId = 1 or ReceiverId = 1)
更新可以是例如id列,如果你在messages
表中
WHERE SenderId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
or ReceiverId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 )
id IN (SELECT id FROM Messages WHERE SenderId = 1 or ReceiverId = 1)
答案 1 :(得分:1)
无需IN()
搜索
SELECT *
FROM Messages
WHERE
(SenderId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 ) and
ReceiverId = 1) or
(ReceiverId = (SELECT UserId FROM Users WHERE ContactNo = 03005114812 ) and
SenderId = 1)
或者:
SELECT m.*
FROM Messages m
INNER JOIN
Users u
on
(m.SenderId = u.UserId and m.ReceiverId = 1) or
(m.ReceiverId = u.UserId and m.SenderId = 1)
WHERE
u.ContactNo = 03005114812
感觉它的重复次数少了一点。