我有2张桌子: 类,Oglasi
categories
category_id | category | parent
1 auto 0
2 games 0
3 bmw 1
4 cards 2
oglasi
oglas_id | category_id
1 3
2 4
我想要做的是制作一个菜单:
父名称 - 类别名称(此类别中的项目数)
示例:auto - bmw(1)
现在我得到了一个父名称 - 类别名称的树状菜单,但不知道如何将所有这些与计算的行号相关联。这是我的查询和代码:
$kategorije = dbQuerySelect('SELECT a.category parent
, b.category child
FROM categories a
JOIN categories b
ON a.category_id = b.parent
ORDER BY a.category_id');
if ($kategorije)
{
$parent = '';
echo "<ul>";
foreach ($kategorije as $next) {
if ($next['parent'] != $parent) {
if (strlen($parent) > 0) {
echo " </ul>";
echo " </li>";
}
echo " <li>" . $next['parent'];
echo " <ul>";
}
echo " <li>" . $next['child'] . "</li>";
$parent = $next['parent'];
}
echo " </ul>";
echo " </li>";
echo "</ul>";
}
所以在这种情况下,这会返回:
parent | child
auto bmw
games cards
有人可以帮我编辑我的代码并返回每个'子类别'中的行数吗?我在查询中尝试了COUNT的一些变体,但我无法使其正常工作。
答案 0 :(得分:1)
SELECT a.category parent,
b.category child,
(select count(*) from oglasi where category_id = b.category_id) as count
FROM categories a
JOIN categories b
ON a.category_id = b.parent
ORDER BY a.category_id
有了这个,你应该得到:
parent|child|count
auto bmw 1