避免SQL查询中的重复行

时间:2013-03-13 18:45:08

标签: sql sql-server-2008 tsql

我在SQL Server 2008上使用以下SQL查询来从productscategories表中选择行。

SELECT products.idProduct,  sku, description, listPrice, 
   smallImageUrl, isBundleMain, rental, visits 
FROM products, categories_products 
WHERE products.idProduct = categories_products.idProduct 
AND categories_products.idCategory = "& pIdCategory&" 
AND listHidden=0 
AND active=-1 
AND idStore = " &pIdStore& "
ORDER BY description

问题是某些行是重复的。这些重复通常由products.idProduct列确定,因此我想更改查询,以便相同的products.idProduct不会出现两次,例如,其中一行有products.idProduct = 3438和其他行具有相同的产品ID,只有products.idProduct中的一个显示

3 个答案:

答案 0 :(得分:6)

你需要使用不同的。请尝试以下

SELECT distinct 
  products.idProduct, sku, description, listPrice, smallImageUrl, 
  isBundleMain, rental, visits 
FROM products, categories_products 
WHERE products.idProduct=categories_products.idProduct 
  AND categories_products.idCategory="& pIdCategory&" 
  AND listHidden=0 AND active=-1 
  AND idStore=" &pIdStore& "  
ORDER BY description

答案 1 :(得分:0)

  

使用DISTINCT,如下所示:

SELECT DISTINCT products.idProduct, 
       sku, description, listPrice, 
       smallImageUrl, isBundleMain, rental, visits 
FROM products, categories_products 
WHERE products.idProduct = categories_products.idProduct 
AND categories_products.idCategory = "& pIdCategory&" 
AND listHidden = 0 AND active = -1 
AND idStore =" &pIdStore& "  
ORDER BY description

答案 2 :(得分:0)

在您的字段上的选择查询中使用DISTINCT。