我有两张桌子:
group --id --name category --id --name --group_id
和查询:
SELECT group.id AS gid, group.name AS gname,
category.id AS cid, category.name AS cname
FROM group join category
on group.id = category.group_id
及其结果如下所示:
gid--gname--cid--cname 1 ---abc----1----def 1 ---abc----2----ggg 2 ---ccc----3----eee 2 ---ccc----4----fff
我想显示一个这样的菜单:
abc --def --ggg ccc --eee --fff
如果我使用该查询,我无法显示上述菜单(事实上,我可以,但很难)。 什么查询或方法可以帮助我做到这一点?非常感谢!
答案 0 :(得分:1)
基本上你必须为每个组循环并打印属于该组的所有类别 在php中你可以这样做:
while( $group = mysql_fetch_array( mysql_query("SELECT id, name FROM group") ) ){
echo $group[1];
while( $category = mysql_fetch_array( mysql_query("SELECT id, name from category where group_id =" . $group[0] ) ) ){
echo $category[1];
}
}
答案 1 :(得分:1)
这是一个演示问题,但您可能会发现在这样的情况下使用GROUP_CONCAT()
来打包每个组的类别
SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name
这是 SQLFiddle 演示
然后在迭代结果集时轻松explode()
php中的列
只是为了让您了解使用PDO
$db = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetchall(PDO::FETCH_ASSOC);
$query = null;
$db = null;
echo '<ul>';
foreach($rows as $row) {
echo '<li>' . $row['gid'] . '-' . $row['gname'];
$categories = explode(',', $row['categories']);
echo '<ul>';
foreach($categories as $category) {
list($cid, $cname) = explode('|', $category);
echo '<li>' . $cid . '-' .$cname . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
输出:
答案 2 :(得分:1)
试试这个:
$arr = array(
array('gid'=>1, 'gname'=>'abc', 'cid'=>1, 'cname'=>'def'),
array('gid'=>1, 'gname'=>'abc', 'cid'=>2, 'cname'=>'ggg'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>3, 'cname'=>'eee'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>4, 'cname'=>'fff'),
);
$res = array();
foreach($arr as $ar){
if(empty($res[$ar['gid']])){
$res[$ar['gid']] = array(
'gid'=>$ar['gid'],
'gname'=>$ar['gname'],
);
}
$res[$ar['gid']]['category'][] = array('cid'=>$ar['cid'],'cname'=>$ar['cname']);
}
print_r($res);