简体   繁体   中英

GROUP BY mysql showing only one row. But want repetitions also

My table structure is

id  order_id  location time    date
 1   951        x              2/03/2013
 2   951        x      13:00   2/03/2013
 3   951        y              3/03/2013

I want to show these in php with group by date something like

Date 2/03/2013
Orderid 951 location x
Orderid 951 location x

Date 3/03/2013
Orderid 951 location y

mysql query im performing is

select * from table where order_id=951 GROUP BY date ORDER BY id ASC

But this query only return the first row of same data . How can i show all the repetition in group by date category. how to use it in php to show data by taking date as separate variable.

i am editing question to let you know that date can be anything i just want order id to show by date in group including repetition.

If you want to show all rows in the table, better to ORDER BY date, id then do the grouping in PHP.

$result = mysql_query("select * from table ORDER BY data ASC,id ASC");
$last_date = "";
while(($row=mysql_fetch_assoc($result)))
{
    if($last_date != $row['date'])
    {
        echo "Date " . $row['date'] . "\n";
    }
    echo "Orderid ". $row['order_id']." location " . $row['location']. "\n";
}

Use STR_TO_DATE() function for ordering by date

$result = mysql_query("select * from table ORDER BY STR_TO_DATE(date, '%d/%m/%Y') ASC, id ASC");
$last_date = "";
while(($row=mysql_fetch_assoc($result)))
{
    if($last_date != $row['date'])
    {
        echo "Date " . $row['date'] . "\n";
    }
    echo "Orderid ". $row['order_id']." location " . $row['location']. "\n";
}
select * from table where order_id=951 ORDER BY date DESC, id ASC

And then manipulate from PHP

Order By will not return rows inside grouping. If you really wanted to use sql then you try GROUP_CONCAT which returns grouped row values as a concatenated string and later split it from PHP.

Since your table owned the time column maybe you should consider inside your query, order is default by ascending, so you can skip for writing asc .

select * from table where order_id=951 order by date,time,id;

You can create a global php variable to store the current date you read, compare everytime in the while loop, and if it's different from the global one, print something to separate from the last group.

另一种解决方案是使用GROUP_CONCAT

select date,group_concat("Location " , location, "\\n") from table where order_id=951 GROUP BY date ORDER BY id ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM