2012-12-31 27 views
1

我有列Sections中存儲在數據庫中的部分列表(sectionId, sectionTypeId, sectionName)和表UserPrivilages中的列與列(userPrivilagesId, userId, sectionTypeId)的權限。選擇所有部分並使用用戶特權標記

我想選擇從表Sections所有部分,但這些標記通過sectionTypes通過sectionTypeId存儲userIdUserPrivilages

喜歡的東西:

SELECT sectionId, sectionTypeId, sectionName, (true/false) as privilage 
FROM Sections 

如果我加入這個與表UserPrivilages我得到的結果只有兩個表中存在,但我想有也第用戶不要t have privilages`了。

這真/假如有以下sectionTypeIdSections表由userId存在UserPrivilages表比返回true UserPrivilages表,否則爲假

那麼結果將是例如

SectionId sectionTypeId sectionName privilage 
1   1    Name1   true or 1 
2   2    Name2   false or 0 
+0

這是**特權** - 不特權... –

回答

3

這聽起來像你想要一個左連接,可能是一個COALESCE代替回答時的privilages不存在行:

SELECT 
    s.sectionId, 
    s.sectionTypeId, 
    s.sectionName, 
    COALESCE(p.privilage,0) as privilage 
FROM 
    Sections s 
    left join 
    Privilages p 
    on 
     s.sectionTypeId = p.sectionTypeId and 
     p.UserId = @User 

這將有一個0只要不存在匹配。


,或者可能重新閱讀的問題,你是不是從p選擇列,你只是要檢查是否存在:

SELECT 
    s.sectionId, 
    s.sectionTypeId, 
    s.sectionName, 
    CASE WHEN p.userPrivilagesId is NULL THEN 0 ELSE 1 END as privilage 
FROM 
    Sections s 
    left join 
    Privilages p 
    on 
     s.sectionTypeId = p.sectionTypeId and 
     p.UserId = @User 

(假設userPrivilagesId是一個非NULL列在p)。

+0

是的,這對我來說是唯一的問題是,我沒有存儲此特權在UserPrivilages表中它不會返回true/false我可以chane這p.privilage與p.userPrivilagesId並獲得正確的結果,但它不會返回true/false,但id/false。如何在UserPrivilages表中沒有此真/假保留的情況下管理該問題。 – janilemy

+0

@janilemy - 我用第二個查詢更新了我的答案 - 你見過那個嗎?它只是基於'privilages'表(也,它通常是拼寫特權) –

+1

O.k這第二種解決方案是爲我好現有的或沒有行返回0或1。謝謝你的幫助 – janilemy

相關問題