MySQL多对多分组

时间:2011-03-11 18:49:25

标签: php mysql sql

我有以下表格,包含以下属性:

位置 - location_id,名称

日程 - schedule_id,名称

locatoin_schedule - location_id,schedule_id

我正在使用这样的查询。

SELECT l.name as locationName, s.name as scheduleName
FROM location AS l, schedule AS s, location_schedule AS ls
WHERE ls.schedule_id = s.schedule_id
AND ls.location_id = l.location_id

这将返回一个如下所示的数组:

Array
(
    [0] => stdClass Object
        (
            [locationName] => testing
            [scheduleName] => New Schedule
        )

    [1] => stdClass Object
        (
            [locationName] => another
            [scheduleName] => New Schedule
        )

    [2] => stdClass Object
        (
            [locationName] => testing
            [scheduleName] => Another Schedule
        )

)

如果某个位置包含许多时间表,如testing位置的情况,是否可以返回多维数据集?所以我的预期结果将是一个只有2个索引的数组,而不是3 ...但是测试locationName将包含一个包含两个时间表的数组。

我希望这是有道理的,谢谢你的回答。

1 个答案:

答案 0 :(得分:4)

您要么将当前查询处理到所需的数据结构,要么使用GROUP_CONCAT然后将日程表字符串拆分为所需的结构。我坚持第一个,因为它更干净,查询更快。

$q="
SELECT l.name as locationName, s.name as scheduleName 
FROM location AS l JOIN schedule AS s ON ls.schedule_id = s.schedule_id 
 JOIN location_schedule AS ls
  ON ls.location_id = l.location_id";
$r=$db->query($q)
while($arr=$r->fetch_assoc()){
  $data[$arr['locationName']][]=$arr['scheduleName'];
}

或GROUP_CONCAT选项:

$q="
SELECT l.name as locationName, GROUP_CONCAT(s.name) as scheduleName 
FROM location AS l JOIN schedule AS s ON ls.schedule_id = s.schedule_id 
 JOIN location_schedule AS ls
  ON ls.location_id = l.location_id
GROUP BY locationName";
$r=$db->query($q)
while($arr=$r->fetch_assoc()){
  $schedules=explode($arr['scheduleName']);
  $data[$arr['locationName']]=$schedules
}