8

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

1
  • 1
    Please qualify your select list so that we can determine which field is coming from which table (e.g.: tablename.sku, tablename.description, etc.). Otherwise, it is impossible to tell if a DISTINCT like some have suggested would fix this. Also, please provide sample result set (showing the duplicate records). Commented Mar 13, 2013 at 19:31

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was discontinued with the ANSI-92 SQL Standard (20 years ago!). Please stop using it
Bad habits to kick: using DISTINCT when there is an underlying data quality or modelling issue. I would say this is a worse habit than join syntax.
3

Use DISTINCT as shown 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

1 Comment

Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was discontinued with the ANSI-92 SQL Standard (20 years ago!). Please stop using it
3

Use DISTINCT in your select query on your fields.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.