Ramaraju.d
Ramaraju.d

Reputation: 1363

select query to get all values and also distinct value

Hi i am trying to get distinct values and some other data from same table A . the code i tried is

$query2="select DISTINCT(from_id) from messages where to_id='$userid' order by messagedate DESC";
$res2=mysql_query($query2);
while($row2=mysql_fetch_row($res2))
{
$query="select * from messages where to_id='$userid' and from_id='$row2[0]' ORDER BY messagedate DESC"

using the above method i am unable to filter distinct values hence i tried like this

select msgid,DISTINCT(from_id) from messages where to_id='21' order by messagedate DESC

Its an error. need help pls

Upvotes: 0

Views: 197

Answers (2)

Paras
Paras

Reputation: 3067

Try like this

select DISTINCT(from_id),msgid from messages where to_id='21' order by from_id DESC

Upvotes: 1

Petah
Petah

Reputation: 46060

Look into the GROUP BY statement

I think you need something like

SELECT    msgid, from_id 
FROM      messages
WHERE     to_id = 21
GROUP BY  from_id
ORDER BY  messagedata DESC

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Upvotes: 0

Related Questions