PDA

View Full Version : a problem with make a query


mamay
08-15-2004, 04:21 AM
I've got a db that has some fileds like 'product_id' ,'sell_date',..
there is a page in my program that user can enter a year number and submit the page to see all the days in that year
that a product is selled with the number of sell in that special day.
I could do this with a query for each day (I mean 365 queries) in tow for loops,one for month and anothe for day:

<?
for($month=1;$month<=12;$month++)
for($day=1;$day<=31;$day++)
{
$res = mysql_query("Select count(*) From mytable Where sell_date='$year-$month-$day'",$handle)

if( $data = mysql_fetch_array($res) )
echo $year."-".$month."-".$day.":".$data[0];
.....
}
?>
but it will take a long time to do 365 queries!
Is there another way that I can do this task with just one query?
Thanks in advance.

raf
08-15-2004, 10:36 AM
$res = mysql_query("SELECT COUNT(*) AS numrecords FROM mytable WHERE sell_date='$year-$month-$day' GROUP BY sell_date",$handle)

mamay
08-15-2004, 01:51 PM
Can you explain me a little more..
I want the number of data in all the days of a year, not just one day.

raf
08-15-2004, 03:35 PM
ha yeay. didn"t realy look at your query.

You need:

$res = mysql_query("SELECT COUNT(*) AS numrecords FROM mytable GROUP BY sell_date",$handle)

this will first group all records by their sell_data and will then count haw many there are for each group.

You could also order the returned records so that the dates with the highest count coma on top :
$res = mysql_query("SELECT COUNT(*) AS numrecords FROM mytable GROUP BY sell_date ORDER BY numrecords DESC",$handle)

or chronologically (counting backwards):
$res = mysql_query("SELECT COUNT(*) AS numrecords FROM mytable GROUP BY sell_date ORDER BY sell_date DESC",$handle)

mamay
08-16-2004, 05:58 AM
you realy made me happy
thanks.

raf
08-16-2004, 09:28 AM
glad you got it runnig :thumbsup: