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
} 
1
  • Try select DISTINCT id from table where comment !='' ORDER BY id Commented Aug 12, 2014 at 5:15

2 Answers 2

2

Try this code

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

It will give you the distinct id from your table

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

1 Comment

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": stackoverflow.com/questions/7188542/db2-comma-separated-output
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 !=''

4 Comments

and how to print them
this may solve my problem but i dont know how to print the the values
it says call to undefined function :(
echo mysql_result($result, 0);

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.