如何在sql中区分重复记录?

时间:2016-10-24 14:00:57

标签: sql-server stored-procedures

您好我有两张名为ArtPlace和PhotoTable的桌子。我将artPlace表中的位置及其照片存储到photoTable中,并将我作为ObjectId的地方ID传递给PhotoTable。对于我为一个地方记录的任何图像,它添加了具有相同ObjectId的记录。当我想要检索我想要的艺术场所时得到一个记录; 这是我的代码示例和结果:

SELECT ArtPlace.Id ,
       PhotoTable.ObjectId,
       ArtPlace.ArtPlaceName,
       ArtPlace.Address,
       ArtPlace.Title,
       ArtPlace.Summary,
       ArtPlace.Description,
       ArtPlace.Visitor,
       ArtPlace.Website,
       PhotoTable.PhotoName
FROM ArtPlace
INNER JOIN City ON ArtPlace.CityId = City.Id
INNER JOIN PhotoTable ON( dbo.PhotoTable.ObjectId = dbo.ArtPlace.Id and dbo.PhotoTable.CategoryId = 5 )
WHERE ArtPlace.CityId = @CityId AND 
      dbo.ArtPlace.IsActive = 1 AND 
      dbo.PhotoTable.CategoryId = 5

END;

here is the result: please click on it to see 唯一的区别在于photoName colunm

2 个答案:

答案 0 :(得分:1)

我认为这里的问题是与PhotoTable的JOIN,因为对于该位置的每张图片,它返回带有位置详细信息的行。我的建议是用EXISTS子句替换连接,并从结果集中删除PhotoTable.PhotoName和PhotoTable.ObjectId。这样,您只会在没有任何照片详细信息的情况下查看位置。

SELECT ArtPlace.Id ,
        ArtPlace.ArtPlaceName,
        ArtPlace.Address,
        ArtPlace.Title,
        ArtPlace.Summary,
        ArtPlace.Description,
        ArtPlace.Visitor,
        ArtPlace.Website
 FROM ArtPlace
      INNER JOIN City ON ArtPlace.CityId = City.Id
 WHERE ArtPlace.CityId = @CityId
       AND dbo.ArtPlace.IsActive = 1
       AND EXISTS(SELECT 1 FROM PhotoTable WHERE dbo.PhotoTable.ObjectId = dbo.ArtPlace.Id and dbo.PhotoTable.CategoryId = 5 )

另外我建议删除CategoryId = 5的硬编码,如果不能使用纯参数,则将其设为默认值的参数。

答案 1 :(得分:1)

您查询给出正确的结果,但如果您只想要一条记录,那么您可以使用ROW_NUMBER

;WITH CTE AS (
       SELECT 
         ROW_NUMBER() OVER(PARTITION BY ArtPlace.Id ORDER BY ArtPlace.Id) RN,
         ArtPlace.Id ,
         PhotoTable.ObjectId,
         ArtPlace.ArtPlaceName,
         ArtPlace.Address,
         ArtPlace.Title,
         ArtPlace.Summary,
         ArtPlace.Description,
         ArtPlace.Visitor,
         ArtPlace.Website,
         PhotoTable.PhotoName
     FROM ArtPlace
     INNER JOIN City ON ArtPlace.CityId = City.Id
     INNER JOIN PhotoTable ON dbo.PhotoTable.ObjectId = dbo.ArtPlace.Id
     WHERE ArtPlace.CityId = @CityId AND 
     dbo.ArtPlace.IsActive = 1 AND 
     dbo.PhotoTable.CategoryId = 5
  )
  SELECT * 
  FROM CTE
  WHERE RN=1