连接两个选择查询会导致每个值一行?

时间:2012-05-19 09:06:28

标签: sql sql-server sql-server-2008 sql-server-2005

我有一个名为CharUser的表有以下数据

UserID UserName UserPhone UserAddress

还有一个名为subscriptionjob

的表格
subID userId   companyid

另一个名为user UsersCvs的表具有以下数据

CVId   Companyuserid   cvpath

我想做一个查询,结果如下每行

userid   username   userphone  useraddress usercv

userid是从subcriptionjob表中提供的 我尝试了以下内容 第一个查询

SELECT        CharUserId, CharUserName, CharUserPassword, CharUserMail, CharUserPhone, CharUserAddress, CharUserGender, ProgId, CharUserBirthdate
FROM            CharUser
WHERE        (CharUserId IN
                             (SELECT        CompanyUserId
                                FROM            SubsciptionJob
                                WHERE        (JobId = 1)))

这是第二个查询

SELECT        TOP (1) CvPath
FROM            UsersCvs
WHERE        (CompanyUserId IN
                             (SELECT        CompanyUserId
                                FROM            SubsciptionJob AS SubsciptionJob_1
                                WHERE        (JobId = 1)))
ORDER BY CvId DESC

两个人都很好 我试图将它们组合在一起但是它不起作用

我想将cvpath列附加到第一个查询,每行有一个唯一值

任何想法..?

谢谢

3 个答案:

答案 0 :(得分:0)

一种方法:

SELECT CharUserId
     , CharUserName
     , CharUserPassword
     , CharUserMail
     , CharUserPhone
     , CharUserAddress
     , CharUserGender
     , ProgId
     , CharUserBirthdate
     , (SELECT TOP (1) CvPath
       FROM UsersCvs
       WHERE CompanyUserId IN (SELECT CompanyUserId
                               FROM SubsciptionJob
                               WHERE JobId = 1)
       ORDER BY CvId DESC) AS CvPath    
FROM CharUser
WHERE CharUserId IN (SELECT CompanyUserId
                     FROM  SubsciptionJob
                     WHERE JobId = 1)

答案 1 :(得分:0)

这比上面的回答更有效:

SELECT CharUserId, 
       CharUserName, 
       CharUserPassword, 
       CharUserMail, 
       CharUserPhone, 
       CharUserAddress, 
       CharUserGender, 
       ProgId, 
       CharUserBirthdate,
       (SELECT TOP (1) CvPath FROM UsersCvs c where c.CompanyUserID=X.CharUserID
       FROM CharUser X
       WHERE (CharUserId IN 
                           (SELECT CompanyUserId FROM SubsciptionJob 
                            WHERE (JobId = 1)))

使用订阅表和CharUser表之间的内部联接可能更有效。

答案 2 :(得分:0)

使用ROW_NUMBER()

SELECT CharUserId, CharUserName, CharUserPassword, CharUserMail, 
    CharUserPhone, CharUserAddress, 
    CharUserGender, ProgId, CharUserBirthdate,cvpath
FROM CharUser CU
JOIN subscriptionjob SJ ON SJ.UserId = CU.UserID
INNER JOIN 
(   SELECT cvpath,Companyuserid,
    ROW_NUMBER() OVER (PARTITION BY A.Companyuserid ORDER BY A.CVID DESC) X
    FROM UsersCvs A
)R ON R.X = 1 AND CU.UserID = R.Companyuserid
WHERE JobId = 1