2013-11-22 32 views
-1

作爲示例,我有兩個mysql表「films」和「showtime」,查詢'$ place_id = 2'和'$ date = 2013-11-22'的變量。 showtime表有colomns'id','film_id','place_id','hall_id','time','date';與左連接和顯示結果在html表中的Mysql查詢

films table have colomns'id','title';

我寫的查詢與左連接,因爲一個查詢比一些更好,因爲我認爲:

SELECT `showtime`.`id`, `showtime`.`film_id`, `showtime`.`place_id`, 
`showtime`.`hall_id`, `showtime`.`time`, `showtime`.`date`, `films`.`id`, 
`films`.`title` FROM (`showtime`) 
LEFT JOIN `films` ON `films`.`id` = `showtime`.`film_id` 
WHERE `showtime`.`date` = '2013-11-22' AND `showtime`.`place_id` = '2' 
ORDER BY `films`.`title` asc, `showtime`.`time` asc 

因爲此查詢我得到這個結果:

print_r($result): 

Array (
[0] => stdClass Object (
[id] => 4 [film_id] => 4 [place_id] => 2 [hall_id] => 2 [time] => 09:00:00 
[date] => 2013-11-22 [title] => Hunger Games 2) 
[1] => stdClass Object ([id] => 4 [film_id] => 4 [place_id] => 2 [hall_id] => 2 
[time] => 22:30:00 [date] => 2013-11-22 [title] => Hunger Games 2) 
[2] => stdClass Object ([id] => 1 [film_id] => 1 [place_id] => 2 [hall_id] => 2 
[time] => 09:00:00 [date] => 2013-11-22 [title] => Thor 2) 
[3] => stdClass Object ([id] => 1 [film_id] => 1 [place_id] => 2 [hall_id] => 2 
[time] => 11:00:00 [date] => 2013-11-22 [title] => Thor 2)) 

隨着使用缺省foreach我有這樣的表:

Title   | Time 
__________________________________ 
Hunger games 2 | 09:00:00 
__________________________________ 
Hunger games 2 | 22:30:00 
__________________________________ 
Thor 2   | 09:00:00 
__________________________________ 
Thor 2   | 11:00:00 

我如何可以在php中按標題分組結果以獲得html表像這樣:

Title   | Time 
__________________________________ 
Hunger games 2 | 09:00:00 22:30:00 
__________________________________ 
Thor 2   | 09:00:00 11:00:00 

有什麼建議嗎?可能是我選擇錯誤的方式與查詢?解析複雜連接查詢的結果有什麼更好的方法?謝謝!

+0

您選擇使用的所有字段?或者只是查詢來創建表? – Jim

+0

這只是一個簡單的例子,瞭解如何將連接查詢中的結果分組。我得到了正確的答案 - group_concat函數。謝謝! – shdq

+0

沒問題。很高興我能幫上忙 :) – Jim

回答

1

假設查詢只用於生產可以使用GROUP BYGROUP_CONCAT表:

SELECT `films`.`title` 
GROUP_CONCAT(`showtime`.`time`) AS filmtime 
FROM (`showtime`) 
LEFT JOIN `films` ON `films`.`id` = `showtime`.`film_id` 
WHERE `showtime`.`date` = '2013-11-22' AND `showtime`.`place_id` = '2' 
GROUP BY films.id 
ORDER BY `films`.`title` asc, `showtime`.`time` asc 

會產生類似於你的第二個表的結果。你可以在你當前的循環中使用它。