Reputation: 5
In the SQL query below, I have 2 tables, documents and document user map. In documents table it has columns documentId, documentname and userid; and in doumnent usermap table it has documentid and userid. The documents that we create will be in documenttable (created documentid, userid). The documents we share to other users will be in documentusermap table (documentid .other userid).here i have to pass my userid to sp
My aim is I want to get documents what other users shared for me.
@i_userid int,
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM Documents Doc
LEFT OUTER JOIN DocumentUserMapping DUM
ON DUM.DocumentID = Doc.DocumentID
AND DUM.UserID != Doc.UserID
Upvotes: 0
Views: 89
Reputation: 1258
Hard to understand your question but if I did understand it this is what you want - a list of documents that are shared to you, but excluding docs that you own. There's no reason this would be a LEFT join in this case.
-- Return documents shared to me that I do not own
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM Documents Doc
JOIN DocumentUserMapping DUM
ON DUM.DocumentID = Doc.DocumentID
AND DUM.UserID = @i_userid -- Shared to me
WHERE Doc.UserID != @i_userid -- Not owned by me
Alternatively you want both docs you own, AND docs shared to you; simplest way shown below:
-- Return documents shared to me AS WELL AS docs I own
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM Documents Doc
WHERE Doc.UserID = @i_userid -- Docs I own
-- Or.. Docs shared
OR EXISTS (SELECT 1 FROM DocumentUserMapping WHERE DocumentID = Doc.DocumentID AND UserID = @i_userid)
Upvotes: 1
Reputation: 3681
Try this query
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM Documents Doc
JOIN DocumentUserMapping DUM
ON DUM.DocumentID = Doc.DocumentID
WHERE Doc.UserID != @i_userid
AND DUM.UserID = @i_userid
Upvotes: 0
Reputation: 3684
I would start by looking for document that are shared to me in the DocumentUserMapping
to then get the document information
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM DocumentUserMapping DUM
INNER JOIN Documents Doc ON DUM.DocumentID = Doc.DocumentID
WHERE DUM.UserID = %myID%
Upvotes: 0
Reputation: 4354
Try this
SELECT Doc.UserID,
Doc.DocumentID,
Doc.DocumentName
FROM Documents Doc
LEFT JOIN DocumentUserMapping DUM
ON Doc.DocumentID = DUM.DocumentID
where Doc.UserID=101;
here I've taken 101 as your user id
Upvotes: 0