Search code examples
mysqlsqldistinctwhere-clause

In a table how to select distinct values of one column by keeping reference of other column?


In my table i have CategoryID and ProductName, here CategoryID has duplicate values. How do i select ProductName with distinct categoryID?

I have tried stack overflow answers which appeared similar but none of them helped.

    +++++++++++++++  ++++++++++++++
    + ProductName +  + CategoryID +
    +++++++++++++++  ++++++++++++++
        Mac                1
        HP                 3
        Walker             1
        Bell               2
        Dell               4   
        Lenovo             3
        Pixel              2

The result should be

    +++++++++++++++  ++++++++++++++
    + ProductName +  + CategoryID +
    +++++++++++++++  ++++++++++++++
        Mac                1
        HP                 3 
        Bell               2
        Dell               4   

Solution

  • You only need to group by categoryid and get the minimum (or maximum?) productname:

    select categoryid, min(productname) as productname
    from tablename
    group by categoryid