简体   繁体   中英

how to get data collectively from table columns

i have such a table:

r_id     date       recipe_name

 1   2012-05-20  Cheese Bread
 1   2012-05-21  Cheese pie
 2   2012-05-20  Spanish Bread

I would like to get all the data under r_id 1 to be in a single row how can i do that using Sql.I need to achieve something like this:

 r_id      recipe_name

 1    Cheese Bread,Cheese pie
 2    Spanish Bread

how can i do this using php too?

Use GROUP_CONCAT

SELECT r_id, GROUP_CONCAT(recipe_name)
FROM yourTable
GROUP BY r_id

Here's the php version

$query = "SELECT id, recipe_name FROM myTable";
$rs = mysqli_query($query);
$results = array();

while($r = mysqli_fetch_assoc($rs)) {
    $results[$r['id']][] = $r['recipe_name'];
    //$results[$r['id']][] = "<a href=''>".$r['recipe_name']."</a>";
}

foreach($results as $id => $recipes) {
    print $id . ' ' . implode(',', $recipes) . "<br>";
}

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