避免 SQL 查询中的重复行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15393833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:14:45  来源:igfitidea点击:

Avoid duplicate rows in SQL query

sqlsql-server-2008tsql

提问by user580950

I use the following SQL query on SQL Server 2008 to select rows from productsand categoriestables.

我使用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

The problem is that some rows are duplicate. Those duplicates are generally determined by products.idProductcolumn, so I want to change the query so that the same products.idProductdoesn't appear twice, means for example one of the rows has products.idProduct = 3438and the other row has same product id as well only one of the products.idProductgets displayed

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

回答by DevelopmentIsMyPassion

You need to use distinct. Try below

您需要使用不同的。试试下面

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

回答by Praveen Nambiar

Use DISTINCTas shown below:

使用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

回答by Apollo SOFTWARE

Use DISTINCT in your select query on your fields.

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