如何从多个表中选择非重复记录

时间:2019-02-08 19:07:19

标签: sql sql-server tsql

在数据库中,我有4个相关的表,我想选择非重复记录,但我不知道该怎么做。

SELECT
    UserID = dbo.tblUsers.id
    ,dbo.tblUsers.nickname
    ,dbo.tblUsers.avatarPic
    ,dbo.tblUsers.userRate
    ,dbo.tblUsers.workedProjects
    ,dbo.tblUsersVotes.userVotes
    ,dbo.tblUsersVotes.votesCount
    ,dbo.tblUsersVotes.votesPoint
    ,dbo.tblUsersVotes.voteSticker
    ,dbo.tblUsersVotes.voteMedal
    ,OID = dbo.tblProjectOffers.id
    ,dbo.tblProjectOffers.odate
    ,ProjectID = dbo.tblProjects.id
    ,dbo.tblProjectOffers.oprice
FROM dbo.tblProjectOffers
INNER JOIN dbo.tblUsersVotes
INNER JOIN dbo.tblUsers ON dbo.tblUsersVotes.uid = dbo.tblUsers.id
INNER JOIN dbo.tblProjects ON dbo.tblUsers.id = dbo.tblProjects.UserID ON dbo.tblProjectOffers.pid = dbo.tblProjects.id
WHERE dbo.tblProjectOffers.pid = @pid

在此选择查询中,它显示所有记录,但也包含重复记录。 例如,我希望它仅返回带有1个UserID的1条记录。

这是我的桌子

enter image description here

用户投票样本

sample of user votes

表格和结果

tables and result

2 个答案:

答案 0 :(得分:0)

尝试一下

SELECT DISTINCT
    UserID = dbo.tblUsers.id
    ,dbo.tblUsers.nickname
    ,dbo.tblUsers.avatarPic
    ,dbo.tblUsers.userRate
    ,dbo.tblUsers.workedProjects
    ,dbo.tblUsersVotes.userVotes
    ,dbo.tblUsersVotes.votesCount
    ,dbo.tblUsersVotes.votesPoint
    ,dbo.tblUsersVotes.voteSticker
    ,dbo.tblUsersVotes.voteMedal
    ,OID = dbo.tblProjectOffers.id
    ,dbo.tblProjectOffers.odate
    ,ProjectID = dbo.tblProjects.id
    ,dbo.tblProjectOffers.oprice
FROM dbo.tblProjectOffers
INNER JOIN dbo.tblUsersVotes
INNER JOIN dbo.tblUsers ON dbo.tblUsersVotes.uid = dbo.tblUsers.id
INNER JOIN dbo.tblProjects ON dbo.tblUsers.id = dbo.tblProjects.UserID ON dbo.tblProjectOffers.pid = dbo.tblProjects.id
WHERE dbo.tblProjectOffers.pid = @pid

答案 1 :(得分:0)

您可以使用此

SELECT     
   distinct dbo.tblUsers.id
,dbo.tblUsers.nickname
,dbo.tblUsers.avatarPic
,dbo.tblUsers.userRate
,dbo.tblUsers.workedProjects
,dbo.tblUsersVotes.userVotes
,dbo.tblUsersVotes.votesCount
,dbo.tblUsersVotes.votesPoint
,dbo.tblUsersVotes.voteSticker
,dbo.tblUsersVotes.voteMedal
,dbo.tblProjectOffers.id
,dbo.tblProjectOffers.odate
,dbo.tblProjects.id
,dbo.tblProjectOffers.oprice
FROM dbo.tblProjectOffers
INNER JOIN dbo.tblUsersVotes
INNER JOIN dbo.tblUsers ON dbo.tblUsersVotes.uid = dbo.tblUsers.id
INNER JOIN dbo.tblProjects ON dbo.tblUsers.id = dbo.tblProjects.UserID ON 
dbo.tblProjectOffers.pid = dbo.tblProjects.id
WHERE dbo.tblProjectOffers.pid = @pid

FROM    
    dbo.tblProjectOffers 
INNER JOIN
    dbo.tblUsersVotes 
INNER JOIN
    dbo.tblUsers ON dbo.tblUsersVotes.uid = dbo.tblUsers.id 
INNER JOIN
    dbo.tblProjects ON dbo.tblUsers.id = dbo.tblProjects.UserID ON dbo.tblProjectOffers.pid = dbo.tblProjects.id
where 
    dbo.tblProjectOffers.pid=@pid