简体   繁体   中英

MySQL Many to Many Grouping

I have the following tables with these attributes:

location - location_id, name

schedule - schedule_id, name

locatoin_schedule - location_id, schedule_id

I am using a query like this.

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

This is returning an array that looks like this:

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
        )

)

Is it possible to have this return a multidimensional array of schedules if a location has many schedules as is the case with the testing location? So my intended outcome will be an array with only 2 indexes, rather than 3... but the testing locationName will contain an array with two schedules.

I hope this makes sense, thanks for your answer.

You're stuck either processing the current query into the datastructure you want, or using GROUP_CONCAT and then splitting the schedules string into the structure you want. I'd stick with the first because it's cleaner and the query is faster.

$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'];
}

or the GROUP_CONCAT option:

$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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM