create table PrivateMessage
(
Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
SenderAccountId INT NOT NULL DEFAULT 1,
AcceptorAccountId int NOT NULL DEFAULT 1
);create table Account
(
Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Nick NVARCHAR(25) NOT NULL UNIQUE DEFAULT N'Пользователь'
);
Имеются 2 таблицы. В таблице Account представлены Id аккаунта, которые могут присутствовать в SenderAccountId или AcceptorAccountId, и ник пользователя с таким Id. В таблице PrivateMessage представлены Id сообщения, Id аккаунта автора сообщения - SenderAccountId - и Id аккаунта получателя сообщения - AcceptorAccountId. На вход процедуры поступает Id аккаунта пользователя, для которого нужно получить Id аккаунтов и Nick пользователей, которые хотя бы раз писали сообщение этому пользователю или получали сообщение от него. Моя попытка:
SELECT Id,Nick from Account where Id
in((select SenderAccountId from PrivateMessage
WHERE SenderAccountId=@AccountId)union
(select AcceptorAccountId from PrivateMessage
where AcceptorAccountId=@AccountId))
intersect select Id from Account where Id=@AccountId;
Вот моя вторая попытка, но я не уверен в его правильности:
select distinct Account.Id,Nick from Account
inner join PrivateMessage on SenderAccountId!=AcceptorAccountId
where (Account.Id!=@AccountId)and(SenderAccountId=@AccountId or AcceptorAccountId=@AccountId);
Подскажите, правильно ли выводит этот запрос?
P.S. В итоге получилась такая процедура:
CREATE PROCEDURE GetPrivateMessagesAuthors(@AccountId int=1)
AS
BEGIN
(select distinct Account.Id,Nick from Account
inner join PrivateMessage on Account.Id=SenderAccountId
where AcceptorAccountId=@AccountId)union
(select distinct Account.Id,Nick from Account
inner join PrivateMessage on Account.Id=AcceptorAccountId
where SenderAccountId=@AccountId);
end
Можно ли написать ещё более оптимальный запрос?