如何在主键在另一个表中作为外键存在两次时查询数据?

时间:2013-01-28 09:26:00

标签: sql-server join distinct

我正在尝试查询数据,但它显示两次相同的记录如何区分?

表1:UserBasics

user_Id , user_Fullname , user_Zip , user_Need
--------------------------------------------------------------------
10    Alberto Cesaro    98001    Sales, Marketing & Public Relations    

表2:UserProfession

Prof_ID , Company , Designation
----------------------------------
10    Young's   Marketing Manager
10    Young's   Regional Manager

我的程序:

CREATE PROC P @Zip         VARCHAR(20)=NULL,
              @Company     VARCHAR(200)=NULL,
              @Designation VARCHAR(100)=NULL,
              @Interest    VARCHAR(200)=NULL,
              @CurrentID   VARCHAR(200)=NULL
--@JobFunc varchar(200)=NULL
AS
  BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      SELECT ub.user_Id,
             ub.user_Fullname,
             up.Designation,
             up.Company
      FROM   UserBasics UB
             INNER JOIN UserProfession up
               ON ub.user_Id = up.Prof_ID
      WHERE  ( @Zip IS NULL
                OR ub.user_Zip LIKE '%' + @Zip + '%' )
             AND ( @Interest IS NULL
                    OR ub.user_Need LIKE '%' + @Interest + '%' )
             AND ( @Company IS NULL
                    OR up.Company LIKE '%' + @Company + '%' )
             AND ( ub.user_Id != @CurrentID )
             AND ( @Designation IS NULL
                    OR up.Designation LIKE '%' + @Designation + '%' )
  END 

如上所述使用存储过程只是为了使条件和变量清晰

如何向每个用户数据显示您的建议的明确希望?

谢谢!

编辑:

输出应该看起来很相似,

10  Alberto Cesaro          Marketing Manager,Regional Manager  Young's

第二次编辑:

我已经完成了公司名称,但是如果我想在用户专业表列上使用过滤器有一些问题那么我将如何联系它?我的询问,

    SELECT
     user_Id, user_Fullname,
     STUFF(
         (SELECT ', ' + Designation 
          FROM   UserProfession as up
          WHERE  Prof_ID = a.user_Id
          FOR XML PATH (''))
          , 1, 1, '') Designation,
      STUFF(
         (SELECT ', ' + Company 
          FROM   UserProfession
          WHERE  Prof_ID = a.user_Id
          FOR XML PATH (''))
          , 1, 1, '')  AS Company
FROM UserBasics AS a
where  (@Zip is null or a.user_Zip like '%'+@Zip+'%') and
    (@Interest is null or a.user_Need like '%'+@Interest+'%') and
    --  (@JobFunc is null or m.mentor_jobFunction= @JobFunc) and
    (@Company is null or up.Company like '%'+@Company+'%') and
    (a.user_Id != @CurrentID) and
    (@Designation is null or up.Designation like '%'+@Designation+'%')
--where   a.user_Zip like '%90005%'
-- WHERE clause here
GROUP BY user_Id, user_Fullname

- 因为我在公司和指定中遇到错误,其中的条款希望最后的建议???

1 个答案:

答案 0 :(得分:1)

SELECT
     user_Id, user_Fullname,
     STUFF(
         (SELECT ', ' + Designation
          FROM   UserProfession
          WHERE  Prof_ID = a.user_Id
          FOR XML PATH (''))
          , 1, 1, '')  AS DesignationList
FROM UserBasics AS a
-- WHERE clause here
GROUP BY user_Id, user_Fullname