GROUP BY for Several Columns
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>
mysql> CREATE TABLE languages (
-> langID int(11) NOT NULL auto_increment PRIMARY KEY,
-> langName varchar(40),
-> ts timestamp
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql>
mysql> INSERT INTO languages VALUES (1,'english','2004-12-02 18:37:02'),
-> (2,'deutsch','2004-12-02 18:37:02'),
-> (3,'svensk','2004-12-02 18:37:02'),
-> (4,'norsk','2004-12-02 18:37:02');
Query OK, 4 rows affected (0.00 sec)
Records: 4 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.01 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> SELECT langName, catName, COUNT(*)
-> FROM titles, languages, categories
-> WHERE titles.catID = categories.catID
-> AND titles.langID = languages.langID
-> GROUP BY langName, catName;
Empty set (0.00 sec)
mysql>
mysql>
mysql> drop table titles;
Query OK, 0 rows affected (0.00 sec)
mysql> drop table languages;
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