2013-03-04 72 views
4

我的表結構GROUP BY mysql只顯示一行。但想重複也

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 

我想按日期類似

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

Date 3/03/2013 
Orderid 951 location y 

MySQL查詢即時表演與組PHP來顯示這些被

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

但此查詢只返回相同數據的第一行。我怎樣才能顯示按日期分組的所有重複。如何使用它在PHP中顯示數據通過將日期作爲單獨的變量。

我在編輯問題,讓你知道日期可以是任何我只想要命令ID以包括重複在內的日期顯示。

回答

1

如果要顯示錶中的所有行,最好使用ORDER BY date, id然後在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"; 
} 
+0

是的,可以做到。但有沒有任何MySQL方式來執行此操作。即使我通過ID命令。由於數據是在上一次添加之後添加的,因此它仍然按升序排列。而且我不會在PHP中關於日期分組的事情是健壯的方式。如果數據太多,在PHP中分組將是一個問題。我對嗎。 – Abhishek 2013-03-04 09:30:21

+0

@AbhishekGahlot看到我的答案以asc格式訂購你的日期 – 2013-03-04 09:37:34

1

使用STR_TO_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"; 
} 
+0

如果你想訂購日期,你必須在你的查詢中使用'STR_TO_DATE()'函數 – 2013-03-04 09:34:55

+0

謝謝你的回答。 sql部分幫助了我。 – Abhishek 2013-03-04 09:47:43

+0

太棒了! @AhhishekGahlot你的歡迎 – 2013-03-04 09:48:29

1
select * from table where order_id=951 ORDER BY date DESC, id ASC 

再從PHP

操縱

排序不會內部分組返回行。如果您真的想使用sql,那麼您可以嘗試使用GROUP_CONCAT,它將分組的行值作爲連接字符串返回,並在稍後將其從PHP中分離出來。

0

另一種解決方案是使用GROUP_CONCAT

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

1

因爲你的表所擁有的time列也許你應該查詢裏面考慮,順序是按升序默認情況下,這樣你就可以跳過寫asc

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

您可以創建一個全局PHP變量來存儲讀取當前日期,while循環每次進行比較,如果它是從全球的不一致,打印的東西,從最後一組分開。