Count joined table
mysql>
mysql>
mysql> CREATE TABLE titles (
-> titleID int(11),
-> title varchar(100),
-> subtitle varchar(100),
-> edition tinyint(4),
-> publID int(11),
-> catID int(11),
-> langID int(11),
-> year int(11),
-> isbn varchar(20),
-> comment varchar(255),
-> ts timestamp,
-> authors varchar(255),
-> PRIMARY KEY (titleID)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql>
mysql> INSERT INTO titles VALUES (1,'Linux','Installation',5,1,57,2,2000,NULL,NULL,'2005-02-28 13:34:21','Michael'),
-> (2,'Excel',NULL,NULL,2,3,NULL,2000,NULL,NULL,'2005-02-28 13:34:22','David'),
-> (3,'XML',NULL,NULL,1,2,NULL,1997,NULL,NULL,'2005-02-28 13:34:22','Edwards'),
-> (4,'PHP',NULL,NULL,3,6,NULL,2000,NULL,NULL,'2005-02-28 13:34:22','Tom'),
-> (5,'MySQL','',0,3,34,NULL,2000,'','','2005-02-28 13:34:22','Paul'),
-> (6,'Java',NULL,NULL,4,34,NULL,1999,NULL,NULL,'2005-02-28 13:34:22','Tim');
Query OK, 6 rows affected (0.00 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql>
mysql>
mysql> CREATE TABLE categories (
-> catID int(11) NOT NULL auto_increment PRIMARY KEY ,
-> catName varchar(60),
-> parentCatID int(11),
-> ts timestamp
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql>
mysql> INSERT INTO categories VALUES (1,'Computer books',11,'2004-12-02 18:37:20'),
-> (2,'Databases',1,'2004-12-02 18:37:20'),
-> (3,'Programming',1,'2004-12-02 18:37:20'),
-> (4,'Relational Databases',2,'2004-12-02 18:37:20'),
-> (5,'Object-oriented databases',2,'2004-12-02 18:37:20'),
-> (6,'PHP',3,'2004-12-02 18:37:20'),
-> (7,'Perl',3,'2004-12-02 18:37:20'),
-> (8,'SQL',2,'2004-12-02 18:37:20'),
-> (9,'Children\'s books',11,'2004-12-02 18:37:20'),
-> (10,'Literature and fiction',11,'2004-12-02 18:37:20'),
-> (11,'All books',NULL,'2004-12-02 18:37:20');
Query OK, 11 rows affected (0.00 sec)
Records: 11 Duplicates: 0 Warnings: 0
mysql>
mysql>
mysql>
mysql> SELECT catName, COUNT(title) AS nrOfItems
-> FROM categories LEFT JOIN titles ON titles.catid = categories.catid
-> GROUP BY catname
-> ORDER BY nrOfItems DESC;
+---------------------------+-----------+
| catName | nrOfItems |
+---------------------------+-----------+
| Databases | 1 |
| PHP | 1 |
| Programming | 1 |
| All books | 0 |
| Relational Databases | 0 |
| SQL | 0 |
| Computer books | 0 |
| Object-oriented databases | 0 |
| Children's books | 0 |
| Literature and fiction | 0 |
| Perl | 0 |
+---------------------------+-----------+
11 rows in set (0.00 sec)
mysql>
mysql>
mysql> drop table titles;
Query OK, 0 rows affected (0.00 sec)
mysql> drop table categories;
Query OK, 0 rows affected (0.00 sec)
mysql>
Related examples in the same category