如何从表列集中获取数据

时间:2014-07-21 08:47:27

标签: php sql

我有这样一张桌子:

r_id     date       recipe_name

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

我想将r_id 1下的所有数据放在一行中如何使用Sql实现。我需要实现这样的目标:

 r_id      recipe_name

 1    Cheese Bread,Cheese pie
 2    Spanish Bread

我怎么能用php做到这一点?

2 个答案:

答案 0 :(得分:1)

使用GROUP_CONCAT

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

答案 1 :(得分:0)

这是php版本

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