0

I am working on a project where I need to achieve a special task like this.

I have a sql query which fetches all the ids of users who commented on a post and then I use mysql_fetch_array and while loop to create a string of comma separated ids of those users like this.

If the ids of the users on any post are 1 and 4 and 5 and 18 and 88, the string I get is like 1,4,5,18,88.

But the problem is that if any person has made more than one comment then his/her id is added again I do not want this.

Like the users are:

1,4,5,4,1,15

It gets:

1,4,5,4,1,15

But I want:

1,4,5,15

I don't want duplicates.

What I tried:

select id from table where comment !=''
mysql_fetch_array()
while (){
   // now joining the ids of commenters here but not duplicate ids
} 
SuperAzeem
  • 157
  • 1
  • 11
abhi
  • 15
  • 5

2 Answers2

2

Try this code

SELECT DISTINCT id FROM tablename WHERE  comment !='' ORDER BY id

It will give you the distinct id from your table

Jha
  • 23
  • 10
  • This is one of the rare occasions where `DISTINCT` is actually the correct answer. Also, if the next question is "how do I make a comma-separated list": http://stackoverflow.com/questions/7188542/db2-comma-separated-output – Turophile Aug 12 '14 at 05:30
1

Use group_concat and you don't even need a loop. A single query will do it.

select group_concat(distinct id) from table where comment !=''
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121