2013-02-14 36 views
-1

我試圖根據業務和用戶標識獲取成員。但是這不能正常工作。請幫我解決這個問題。加入3個表格無法正常工作

SELECT distinct m.Fname,m.Created,m.[User_Name],b.Business_Name 
FROM dbo.Members m,dbo.Business b,dbo.Assign_Business a 
WHERE m.Subcriber_id=a.Subscriber_id 
AND a.Business_id=b.id 
AND b.Subcriber_id=a.Subscriber_id 
AND a.Business_id='6' AND a.Subscriber_id='1' 
+1

問題是什麼? – Orangecrush 2013-02-14 05:49:01

+0

感謝您的回覆。「a.Business_id ='6'AND a.Subscriber_id ='1'」部分不會生效。在我更改商戶ID後,如果您刪除了這些條件,它不會檢索正確的值 – TRS 2013-02-14 05:51:17

+0

,輸出是否正確? – 2013-02-14 05:51:58

回答

1

試試這個..

select distinct m.Fname,m.Created,m.[User_Name],b.Business_Name 
from dbo.Members m 
left join dbo.Assign_Business a on m.Subcriber_id=a.Subscriber_id 
left join dbo.Business b on a.Business_id=b.id 
where a.Business_id='6' and a.Subscriber_id='1' and b.Subcriber_id=a.Subscriber_id 
1

第一步,乾淨格式化你的代碼。這對調試有很大的幫助。

SELECT 
    distinct m.Fname, 
      m.Created, 
      m.[User_Name], 
      b.Business_Name 
FROM 
    dbo.Members as M 
    inner join dbo.Assign_Business as A on M.Subscriber_Id = A.Subscriber_id 
    inner join dbo.Business as B on B.id = A.Business_id and B.Subscriber_id = A.Subscriber_id 
WHERE 
    A.Business_ID = '6' 
    and A.Subscriber_id = '1' 
1

很難說沒有看到你的表DDL,但你可以嘗試

SELECT DISTINCT 
     m.Fname,m.Created,m.[User_Name],b.Business_Name 
    FROM dbo.Business b INNER JOIN 
     dbo.Assign_Business a ON a.Business_id=b.id AND 
           a.Subscriber_id=b.Subcriber_id INNER JOIN 
     dbo.Members m ON m.Subcriber_id=a.Subscriber_id 
WHERE a.Business_id=6 AND 
     a.Subscriber_id=1 
1

嘗試以下操作:

SELECT DISTINCT 
    m.Fname, 
    m.Created, 
    m.[User_Name], 
    b.Business_Name 
FROM dbo.Members m 
    INNER JOIN dbo.Assign_Business a ON m.Subcriber_id=a.Subscriber_id 
    INNER JOIN dbo.Business b ON a.Business_id=b.id AND b.Subcriber_id=a.Subscriber_id 
WHERE 
    a.Business_id='6' AND a.Subscriber_id='1'