mysql检索多行到多行

时间:2010-10-18 13:09:29

标签: mysql

当我触发以下查询时,我得到了我需要按event.id分组的结果:

SELECT events.id AS id,events.name AS event,categories.name AS categories
                FROM events,categories,event_dates,event_categories
                WHERE events.preview = 0 AND event_dates.start_date > DATE(NOW())
                    AND events.id = event_dates.event_id AND events.id = event_categories.event_id AND event_categories.category_id = categories.id
                GROUP BY events.id LIMIT 0,5

使用以下结果(event_categories是将事件链接到类别的表):

Array ( [id] => 144 [event] => Twickenham Stadium Tours and World Rugby Museum [name] => Sport ) 

然而,这是多对多关系,此查询仅返回一个类别。如何重新排列/制定一个可以获取所有类别的查询

1 个答案:

答案 0 :(得分:0)

尝试在查询中使用group_concat

    GROUP_CONCAT(DISTINCT categories.name  ORDER BY categories.name SEPARATOR ",") 
AS  categories

所以最终的查询如下:

SELECT events.id AS id,events.name AS event,
GROUP_CONCAT(DISTINCT categories.name  ORDER BY categories.name SEPARATOR ",") 
    AS  categories
                FROM events,categories,event_dates,event_categories
                WHERE events.preview = 0 AND event_dates.start_date > DATE(NOW())
                    AND events.id = event_dates.event_id AND events.id = event_categories.event_id AND event_categories.category_id = categories.id
                GROUP BY events.id LIMIT 0,5