避免 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
Avoid duplicate rows in SQL query
提问by user580950
I use the following SQL query on SQL Server 2008 to select rows from productsand categoriestables.
我使用SQL Server 2008在下面的SQL查询来选择行products和categories表。
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。

