Welcome to WebmasterWorld Guest from 54.145.246.183

Forum Moderators: coopster & jatar k

How to select distinct and unique records from mysql database

   
11:33 am on May 5, 2011 (gmt 0)

5+ Year Member



Hello all,

Can anyone write a code that

How to select distinct and unique records from mysql database desc with limit 4

here is my query i wrote

$q = "SELECT DISTINCT productid FROM table where user='$_SESSION[user]' GROUP BY date ORDER BY uniq_id desc LIMIT 4";

Actually what i want is i need to retrieve last added distinct record(uniq_id) from table...but its randomly retriving



e.g They are totally 8 records in my table..after runnin the code..its showing 4th uniq id..instead of 6th uniq id..i want the 6th record to be displayed


Please give a solution this post..

Thank You !
4:49 pm on May 5, 2011 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



The distinct keyword is generally used for rows where the target value is **not** distinct and there may be multiple rows with that value. Isn't your uniq_id already unique in this table? Maybe not . . . in any case there are ways to do this without needing distinct.

Actually what i want is i need to retrieve last added distinct record(uniq_id) from table...but its randomly retriving


What value do you have to determine "last added?" Usually there is (should be!) a datetime value for the added date, which makes this easier. If not, assuming that table.id is an auto increment field,

$query = "select productid from user='$_SESSION[user]' order by date_added desc limit 1";

$query = "select productid from user='$_SESSION[user]' order by id desc limit 1";

or limit 4 as you originally have it . . . anyway every row should have a unique identifier (and a datetime field) and this becomes very easy.
8:16 pm on May 5, 2011 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



Off topic a bit, but watch for SQL injections. It is generally a good idea to structure queries like the following:


$query = sprintf("select productid from user='%s' order by id desc limit 1",
mysql_real_escape_string($_SESSION['user'])
);


The sprintf just makes it look prettier. :)
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month