开发者

when I run query on view I get 2 record for unique id in sql server

I have two table in SqlServer Member and MemberAdress and I am generating a view vw_Member by executing following query

SELECT     
   m.MemberId, 
   m.MemberName, 
   m.EndCustomer,  
   m.ExpirationDate, 
   ma.DEA, 
   ma.HIN,  
   ma.Address1, 
   ma.Address2,  
   ma.City, 
   ma.State,  
   ma.OfficeContact,
   ma.OfficeContactTitle,  
   ma.OfficeContactEmail  
FROM dbo.Member m
   INNER JOIN dbo.MemberAddress ma ON (m.MemberId = ma.MemberId)

but the problem is that I am generating two record 开发者_开发百科 for unique MemberId

Can Somebody tell me what I am doing wrong ?


Wild guess - there are two rows in MemberAddress with the same MemberId. Maybe there's some concept modelled in there of an address type? If so, you need to decide which of those address types you should be including in this view, or if you always need an address, some decision on how you would prioritise the address types.

For the second, your FROM clause might look something like:

FROM
    dbo.Member m
        INNER JOIN  
    dbo.MemberAddress ma
        ON
            m.MemberId = ma.MemberId
        LEFT JOIN
    dbo.MemberAddress ma_anti
        ON
            m.MemberId = ma_anti.MemberId and
            ma_anti.AddressType > ma.AddressType --priority decision
WHERE
    ma_anti.MemberId is null

Where the join to ma_anti is trying to find a "better" row from MemberAddress than the row selected from ma - if the join succeeds, you don't want that row in your final result set, so that's what the WHERE clause is doing.


  • Are the double member ID rows valid values?
    • eg Can a Member have more then on address
    • Is there a difference in the rows contents?

Making your data fit the schema

  • dbo.Member.MemberId should be a Primary Key
  • dbo dbo.MemberAddress.MemberId should be a foriegn key that maps to Member.MemberId.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜