so, I am having two tables. One with categories
cat_id || cat_name
1 || cat1
2 || cat2
3 || cat3
one with items
item_id || cat_id
1 || 1
2 || 1
3 || 3
Now, I am trying the traditionnal count Item per category. after reading around (like here for exemple) i managed to build a query that retuns to me the number of items per category in the following format
SELECT
item.cat_id,
COUNT(*) item_count
FROM
item AS item
JOIN cat as cat
ON item.cat_id = cat.cat_id
GROUP BY
item.cat_id
----------------------
RESULT:
----------------------
cat_id || item_count
1 || 2
3 || 1
----------------------
So, my problem here, is that I would also love to include categories that have no object... and I have been trying to wrap my head around that i can't figure it out. Something in that format:
----------------------
cat_id || item_count
1 || 2
2 || 0
3 || 1
----------------------
any clues? thank you in advance
SQL query to build exemple:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `cat`
--
DROP TABLE IF EXISTS `cat`;
CREATE TABLE IF NOT EXISTS `cat` (
`cat_id` int(11) NOT NULL,
`cat_name` varchar(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cat`
--
INSERT INTO `cat` (`cat_id`, `cat_name`) VALUES
(1, 'cat1'),
(2, 'cat2'),
(3, 'cat3');
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
DROP TABLE IF EXISTS `item`;
CREATE TABLE IF NOT EXISTS `item` (
`item_id` int(11) NOT NULL,
`cat_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `item`
--
INSERT INTO `item` (`item_id`, `cat_id`) VALUES
(1, 1),
(2, 1),
(3, 1);
COMMIT;