我有两个mysql表“films”和“showtime”,查询'$ place_id = 2'和'$ date = 2013-11-22'的变量作为示例。
showtime表有colomns'id','film_id','place_id','hall_id','time','date';
电影表有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 :(得分:1)
假设查询仅用于生成表格,您可以使用GROUP BY
和GROUP_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
会产生类似于第二张表的结果。您可以在当前循环中使用它。
答案 1 :(得分:0)
尝试使用mysql GROUP_CONCAT函数:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat