我有具有这些属性的下表:

位置-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将包含一个包含两个调度的数组。

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

最佳答案

您将无法将当前查询处理到所需的数据结构中,或者使用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
}

关于php - MySQL多对多分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5277063/

10-13 01:35