1

I got a simple line of code, that fetch the sequel database and populate a category list, these category strings come by a product table, so many product row produce duplicate category entries.

$cat_result = $mysqli -> query("SELECT * FROM products");
while ($cat_row = mysqli_fetch_array($cat_result, MYSQL_NUM)) { 
    if($cat_row['4'] != NULL) { 
        print '<li><a href="/category/'. $cat_row['4'] .'">'. $cat_row['4'] .'</a></li>'; 
    }
}

The current output is like this:

  • Category1
  • Category1
  • Category2
  • Category2

So how I can suppress duplicate entry and got something like this?

  • Category1
  • Category2

Thanks for your help!

10
  • 2
    DISTINCT and/or GROUP BY Commented Feb 11, 2016 at 16:47
  • Hi @Fred-ii- , see you again! So I must to do "SELECT * FROM product GROUP BY category" where I must to use DISTINCT? Commented Feb 11, 2016 at 16:48
  • 2
    $cat_result = $mysqli -> query("SELECT DISTINCT(name) FROM products"); or $cat_result = $mysqli -> query("SELECT * FROM products GROUP BY name"); Commented Feb 11, 2016 at 16:49
  • SELECT DISTINCT WhatEverTheColumnIsCalled FROM products specially as you only use one column, dont retrieve more than you use and you will find that it run quicker as well Commented Feb 11, 2016 at 16:49
  • Ciao Andrea! si, and SELECT DISTINCT col1, col2 FROM TABLE as per dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html - come stai? Commented Feb 11, 2016 at 16:49

2 Answers 2

4

As requested:

You can use either a DISTINCT in SELECT and/or a GROUP BY

I.e.:

SELECT DISTINCT col1, col2 FROM TABLE GROUP BY col_x

as per http://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html

which will avoid duplicates in your query.

Additionally, a WHERE clause could also be useful (later on).

I.e.:

SELECT DISTINCT col1, col2 FROM TABLE WHERE col_x = 'y' GROUP BY col_x

Reference:

Sign up to request clarification or add additional context in comments.

Comments

3

As suggested by everyone above DISTINCT and GROUP BY both can solve your problem, so you can do like below:-

Suppose the column name is category then:-

$cat_result = $mysqli -> query("SELECT DISTINCT(category) FROM products"); 

OR 

$cat_result = $mysqli -> query("SELECT * FROM products GROUP BY category");

Note:- you can choose n number of different column in DISTINCT too as suggested by others. Thanks.

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.