如何在mysql中显示子类别下的项目

时间:2016-05-05 03:25:15

标签: php mysql

我有三张桌子。

categorytbl

cat_id    cat_name
  1       Vehicles
  2       Computers

subcategorytbl

 sub_id      sub_name         sub_parent_id    cat_id
   1         For Rent            0             1
   2         For Sale            0             1
   3         Car for Rent        1             1
   4         Car for Sale        2             1
   5         Motorcycle for Sale 2             1
   6         Boat                2             1
   7         Desktop             0             1

itemtbl

item_id  item_name       sub_id      
  1       Ferrari           3        
  2       Ford              3
  3       Isuzu             3
  4       GMC               4 
  5       Uncategorized     2
  6       Honda             5

从上面的表格中,我试图显示项目列表,子项目和父项子类别。结果应该是:

  For Rent(3) 
   Ferrari - car for Rent
   Ford    - Car For Rent
   Isuzu   - Car For Rent 

 FOR SALE(3)
   GMC           - Car for Sale
   Uncategorized - [empty]
   Honda         - Motorcycle for Sale

这是我的SQL查询:

  SELECT COUNT( itemtbl.cat_id ) AS cnt, categorytbl.cat_id AS cat_id
  FROM (
  categorytbl
   LEFT JOIN itemtbl ON itemtbl.cat_id = categorytbl.cat_id
   )
   LEFT JOIN subcategorytbl ON subcategorytbl.sub_id = itemtbl.sub_id
   GROUP BY cat_id
   ORDER BY cnt DESC 

1 个答案:

答案 0 :(得分:2)

我建议查询数据库中的项目列表,并使用关联数组在php中进行分组。评论如下:

$sql = "select p.sub_name as parent_name,
s.sub_name, i.item_name
from itemtbl i
join subcategorytbl s on s.sub_id = i.sub_id
join subcategorytbl p on p.sub_id = s.sub_parent_id";

$rs = mysqli_query($sql);
$indexed_results = [];

// create an associative array where the key is 
// the parent sub i.e. For Rent etc
// and the value is an array of items
while($r = mysqli_fetch_assoc($rs)) {
    $indexed_results[$r['parent_name']][] = $r;
}

// now loop through each group and display
foreach($indexed_results as $parent_name => $results) {
    print $parent_name . '('.count($results).")\n";

    foreach($results as $result) {
        print $result['item_name'] . ' - ' 
            . $result['sub_name'] . "\n";
    }
}