简体   繁体   中英

Sql Query left outer join

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

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)

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

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%

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM