2

Suppose my db looks like this:

id | person_id | hobby       | time
-----------------------------------
1  | 67        | golf        | mon
2  | 33        | reading     | tues
3  | 67        | baseball    | fri
4  | 67        | golf        | sun

I want to display a list of all the hobbies of person with id 67 on a page.

If I do this:

$query = mysql_query("SELECT * FROM hobbies WHERE person_id = '67'");

while ($row = mysql_fetch_assoc($query)) {

   echo $row['hobby'];

}

I wil get:

golf
baseball
golf

I want duplicate hobbies entered by the same person id to show only once, so it will show:

golf
baseball

And by duplicate I mean however many redundant times the same hobby by the same person is entered in a database (as long as it's more than once it should shown only once).

How can this be done?

2 Answers 2

15
$query = mysql_query("SELECT DISTINCT `hobby` FROM `hobbies` WHERE `person_id` = '67'");

DISTINCT will not show duplicates for hobby.

Documentation.

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

2 Comments

doesn't work for me, it just returns nothing when I change * to DISTINCT. But even if that wasn't so I don't think this will do, because the same hobby by the same person will still be distinct in that there ids will be different as may the column "time".
oops sorry, I implemented it wrong, yes it does work. Best answer in 10 mins. thanks.
2
$query = mysql_query("SELECT * FROM hobbies WHERE person_id = '67' GROUP BY hobby");

while ($row = mysql_fetch_assoc($query)) {
   echo $row['hobby'];
}

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.