计数功能()

时间:2012-05-11 02:25:01

标签: php mysql

我有这两个表,其中包含一些数据样本。我想在每个类别中提取多个分类广告。我试了一下,每次都得到(2)不正确。所以希望有人能帮助我。

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `name` text COLLATE utf8_unicode_ci NOT NULL,
  `subcategory_id` int(2) NOT NULL DEFAULT '0',
  `parent_id` int(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=27 ;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`id`, `name`, `subcategory_id`, `parent_id`) VALUES
(1, 'Announcements', 0, 0),
(2, 'Employment', 0, 0),
(3, 'Items For Sale', 0, 0),
(4, 'Services', 0, 0),
(5, 'Garage Sales', 0, 0),
(6, 'Automobiles', 0, 0),
(7, 'Announcement1', 1, 1),
(8, 'Announcement2', 1, 1),

--
-- Table structure for table `classifieds`
--

CREATE TABLE IF NOT EXISTS `classifieds` (
  `classified_id` int(255) NOT NULL AUTO_INCREMENT,
  `title` text COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `category_id` int(10) NOT NULL,
  `name` text COLLATE utf8_unicode_ci NOT NULL,
  `authorized` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`adid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=177 ;

--
-- Dumping data for table `classifieds`
--

INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(1, 'Test Classified', 'Here is the First Test classified listing.', 1, 1);

INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(2, 'GMC For Sell', 'Looks like new 1979 GMC.', 6, 1);

这里

$query = "SELECT category_id, COUNT(title) FROM classifieds GROUP BY category_id"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result)
$num_items_in_category = $row['COUNT(title)'];
echo "<><a href='category-".$row['id'].".php' >".$row['name'].$num_items_in_category."</a></li>";

由于

2 个答案:

答案 0 :(得分:2)

稍微更改一下SQL,然后遍历结果?

$query = "SELECT c.id, c.name,
                 COUNT(cl.category_id) AS num_items_in_category
              FROM category_id c
                 LEFT JOIN aclassifieds cl ON cl.category_id=c.id
              GROUP BY c.id";  
$result = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($result)) {
    echo "<li><a href='category-".$row['id'].".php' >".$row['name'].$row['num_items_in_category']."</."</a></li>"; 
}

答案 1 :(得分:0)

以防万一其他人想要让我受益:

enter $query = "SELECT c.id, c.name,
             COUNT(cl.title) AS num_items_in_category
          FROM categories c
             LEFT JOIN classifieds cl ON cl.category_id=c.id
          GROUP BY c.id";
  $result = mysql_query($query) or die(mysql_error()); 

while($ row = mysql_fetch_array($ result)){     echo“

  • ”。$ row ['name']。$ row ['num_items_in_category']。“
  • ”; }  这里 感谢