Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicate rows in SQL query

I use the following SQL query on SQL Server 2008 to select rows from products and categories tables.

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.idProduct column, so I want to change the query so that the same products.idProduct doesn't appear twice, means for example one of the rows has products.idProduct = 3438 and the other row has same product id as well only one of the products.idProduct gets displayed

like image 200
user580950 Avatar asked Mar 13 '13 18:03

user580950


People also ask

Why is my SQL query duplicating rows?

This might happen if one of the tables has a compound key and we don't specify all its columns or if we join to a column which is not a unique key.


1 Answers

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
like image 81
DevelopmentIsMyPassion Avatar answered Sep 22 '22 00:09

DevelopmentIsMyPassion