代码如下:
SELECT DISTINCT *
FROM tblWCS_Bulletins
INNER JOIN tblWCS_BulletinComments ON tblWCS_BulletinComments.BulletinID = tblWCS_Bulletins.RowID
WHERE VisibleTo LIKE ('%@' + @UserID + '@%')
AND CommentString LIKE ('%' + @SearchString + '%')
OR VisibleTo LIKE ('%@' + @UserID + '@%')
AND BulletinHeader LIKE ('%' + @SearchString + '%')
OR VisibleTo LIKE ('%@' + @UserID + '@%')
AND BulletinContent LIKE ('%' + @SearchString + '%'
但如果在第二个表中找到多个结果,则返回第一个表中行的重复项。我希望结果只返回第一个表中的一行,即使在找到的第二个连接表中有多行。
答案 0 :(得分:1)
修改您的查询,如下所示,此查询将仅从具有不同值的第一个表中获取数据。
SELECT DISTINCT tblWCS_Bulletins.*
FROM tblWCS_Bulletins
INNER JOIN tblWCS_BulletinComments
ON tblWCS_BulletinComments.BulletinID = tblWCS_Bulletins.RowID
WHERE VisibleTo LIKE ('%@' + @UserID + '@%') AND CommentString LIKE ('%' + @SearchString + '%')
OR VisibleTo LIKE ('%@' + @UserID + '@%') AND BulletinHeader LIKE ('%' + @SearchString + '%')
OR VisibleTo LIKE ('%@' + @UserID + '@%') AND BulletinContent LIKE ('%' + @SearchString + '%'
希望这有帮助!
答案 1 :(得分:1)
大概你想要每BulletinId
行一行:
SELECT *
FROM (SELECT . . ., -- list columns you want
ROW_NUMBER() OVER (PARTITION BY BulletinId ORDER BY BulletinId) as seqnum
FROM tblWCS_Bulletins b INNER JOIN
tblWCS_BulletinComments bc
ON bc.BulletinID = b.RowID
WHERE (VisibleTo LIKE ('%@' + @UserID + '@%') AND CommentString LIKE ('%' + @SearchString + '%')) OR
(VisibleTo LIKE ('%@' + @UserID + '@%') AND BulletinHeader LIKE ('%' + @SearchString + '%')) OR
(VisibleTo LIKE ('%@' + @UserID + '@%') AND BulletinContent LIKE ('%' + @SearchString + '%'))
) x
WHERE seqnum = 1;
您应该明确列出列以避免重复的列名称(子查询中不允许)。
您可以通过调整ORDER BY
子句确定第二个表中的哪一行。