2016-10-01 66 views
0

假設我有一個名爲Document的db表,它包含我擁有的所有文檔的行。我有另一個名爲Shared的db表,它擁有我可以讀/寫的所有文檔(由其他人擁有)的記錄。優化查詢以從兩個表中獲取結果

Document 
id 
type 
user_id 
permissions 

Shared 
id 
document_id 
used_id 
permissions 

我試圖寫一個查詢,讓我回到我(給予user_id)擁有並有權訪問的所有文檔。我的嘗試是這樣的:

Select id, type, user_id, permissions from Document where user_id = 123 
union all 
Select id, type, user_id, permissions from Document where id in 
            (select document_id from shared where user_id = 123) 

上面似乎有點冗長,所以我想知道是否有寫上(如果它在所有工作)

回答

2

嘗試更簡潔/有效的方法使用左加入+ where where子句

Select d.id, d.type, d.user_id, d.permissions from Document d 
left join shared s on s.document_id = d.id 
        and s.user_id = d.user_id 
where d.user_id = 123 
and s.document_id IS NOT NULL 
+0

我對sql有點缺乏經驗,但我認爲document_id = d.id上的聯接需要同時存在於兩個表中的文檔?可能會出現這樣的情況,我希望文檔表中的文檔僅適用於我和文檔表中不存在的文檔,但我有權訪問共享表中的文檔,因爲我的user_id在該表中的一行上,即 –

+0

是左連接+ where子句出現的位置。基本上,它將包含'共享'表中存在的'Document'表中的所有條目,如果它沒有在'shared'表中找到條目,它將返回數據設置爲空,這就是'where where子句出現在哪裏 –

+0

我也更新了答案,使用正確的列名來防止模糊的列名錯誤 –