2015-06-10 50 views
0

我有兩個表。我寫了這個查詢但不顯示錶結果 怎麼寫完美的查詢顯示錶結果?如何在兩個表上編寫完美的查詢連接操作?

Taccess 
id userid groupid accesstype 
    1  2  1   1 
    2  4  1   1 

    Tgroup 
    grugroupid  groupbname  userid 
     1    group-1  1 
     2    group-2  2 
     3    group-3  3 
     4    group-4  4 

我需要這個結果對於用戶ID = 1 我想表明那麼所有GROUPID顯示接入類型的userid = 1

grugroupid   groupbname  accesstype 
     1    group-1   1 
     2    group-2   null 
     3    group-3   null 
     4    group-4   null 

    select grugroupid   , 
      userid ,groupbname  ,  
      (select AccessType from Access where UserID=2) as dd,   
       from TLab_Info 
     union 
     select id userid groupid accesstype 
      from TLab_Access 
+0

你能解釋這些表之間的關係?像外鍵.. –

回答

0

額外的變種已經發布的Raging Bull

SELECT DISTINCT 
     g.grugroupid, 
     g.groupbname, 
     a.accesstype 
FROM Tgroup g LEFT JOIN 
     Taccess a ON g.grugroupid = a.groupid 
WHERE COALESCE(a.accesstype,1) = 1 

測試是在這裏SQL Fiddle

1
SELECT g.grugroupid,g.groupbname,a.accesstype 
FROM Tgroup g LEFT JOIN 
    Taccess a on g.grugroupid=a.groupid 
WHERE (a.accesstype IS NULL) OR (a.accesstype=1) 
GROUP BY g.grugroupid,g.groupbname,a.accesstype 

結果:

grugroupid groupbname accesstype 
---------------------------------- 
1   group-1  1 
2   group-2  (null) 
3   group-3  (null) 
4   group-4  (null) 

參見導致SQL Fiddle

相關問題