Joins, grouping and subqueries
Join tables, group and aggregate, filter groups with HAVING, and use subqueries, UNION and the set operators, with a set of sample tables.
The statements (joins, grouping, subqueries, set operators) were checked against MySQL and MariaDB. The data:
DROP DATABASE IF EXISTS tut3;
CREATE DATABASE tut3;
USE tut3;
CREATE TABLE cust (id INT PRIMARY KEY, name VARCHAR(20) NOT NULL, city VARCHAR(20));
CREATE TABLE ord (id INT PRIMARY KEY, cust_id INT, total DECIMAL(10,2), status VARCHAR(10));
CREATE TABLE line (ord_id INT, sku VARCHAR(10), qty INT);
INSERT INTO cust VALUES (1,'Ann','Oslo'),(2,'Bob','Rome'),(3,'Cy','Oslo'),(4,'Di',NULL);
INSERT INTO ord VALUES (10,1,100.50,'paid'),(11,1,20.00,'new'),(12,2,35.25,'paid'),(13,3,NULL,'new'),(14,9,5.00,'paid');
INSERT INTO line VALUES (10,'a',2),(10,'b',1),(11,'a',5),(12,'c',3),(12,'a',1);Order 14 belongs to a customer (9) who does not exist, and customer Di has no orders.
Inner join#
SELECT c.name, o.id, o.total FROM cust c JOIN ord o ON o.cust_id = c.id ORDER BY o.id;| name | id | total |
|---|---|---|
| Ann | 10 | 100.50 |
| Ann | 11 | 20.00 |
| Bob | 12 | 35.25 |
| Cy | 13 | NULL |
Order 14 has no customer and is not in the result.
Outer joins#
SELECT c.name, o.id FROM cust c LEFT JOIN ord o ON o.cust_id = c.id ORDER BY c.id, o.id;
SELECT c.name, o.id FROM cust c RIGHT JOIN ord o ON o.cust_id = c.id ORDER BY o.id;
SELECT c.name FROM cust c LEFT JOIN ord o ON o.cust_id = c.id WHERE o.id IS NULL;The first lists Di with a NULL order id; the second lists order 14 with a NULL name; the third finds the customers without orders (Di).
More than two tables, and other forms#
SELECT c.name, o.id, l.sku FROM cust c JOIN ord o ON o.cust_id = c.id JOIN line l ON l.ord_id = o.id ORDER BY o.id, l.sku;
SELECT c.name, o.id FROM cust c JOIN ord o USING (id) ORDER BY c.id;
SELECT c.name, o.id FROM cust c, ord o WHERE o.cust_id = c.id AND o.status = 'paid' ORDER BY o.id;
SELECT c.name, o.id FROM cust c CROSS JOIN ord o WHERE o.id = 10 ORDER BY c.id;Grouping#
SELECT city, COUNT(*) FROM cust GROUP BY city ORDER BY city;
SELECT status, COUNT(*) n, SUM(total) s, AVG(total) a, MIN(total) lo, MAX(total) hi FROM ord GROUP BY status ORDER BY status;
SELECT cust_id, SUM(total) t FROM ord GROUP BY cust_id HAVING t > 30 ORDER BY cust_id;
SELECT c.name, COUNT(o.id) n FROM cust c LEFT JOIN ord o ON o.cust_id = c.id GROUP BY c.id, c.name ORDER BY n DESC, c.name;For the second statement: status new has two orders (11 and 13) with a sum of 20.00, because SUM ignores the NULL total; status paid has three orders and a sum of 140.75. The last statement counts the orders of each customer including those with none: Ann 2, Bob 1, Cy 1, Di 0 (COUNT(o.id) does not count the NULL of the outer join).
HAVING filters groups after the aggregation and may use an alias of the select list (t above). The aggregate GROUP_CONCAT lists values:
SELECT status, GROUP_CONCAT(id ORDER BY id SEPARATOR '|') FROM ord GROUP BY status ORDER BY status;GROUP BY ... WITH ROLLUP is supported; it is checked against MariaDB.
Subqueries#
SELECT name FROM cust WHERE id IN (SELECT cust_id FROM ord WHERE status = 'paid') ORDER BY name;
SELECT name FROM cust c WHERE EXISTS (SELECT 1 FROM ord o WHERE o.cust_id = c.id AND o.total > 30) ORDER BY name;
SELECT name, (SELECT COUNT(*) FROM ord o WHERE o.cust_id = c.id) AS n FROM cust c ORDER BY name;
SELECT d.city, d.n FROM (SELECT city, COUNT(*) n FROM cust GROUP BY city) d WHERE d.n > 1;
SELECT id FROM ord o1 WHERE total > (SELECT AVG(total) FROM ord o2 WHERE o2.status = o1.status) ORDER BY id;NOT IN follows SQL's three-valued logic: SELECT name FROM cust WHERE id NOT IN (SELECT cust_id FROM ord) compares with the set of customer ids in ord (1, 2, 3, 9) and finds Di.
Combining queries#
SELECT id FROM cust UNION SELECT cust_id FROM ord ORDER BY id;
SELECT id FROM cust UNION ALL SELECT cust_id FROM ord ORDER BY id;UNION removes duplicates, UNION ALL keeps them. INTERSECT and EXCEPT (with and without ALL) work as follows:
CREATE DATABASE qf1;
USE qf1;
CREATE TABLE a (x INT); CREATE TABLE b (x INT);
INSERT INTO a VALUES (1), (2), (2), (3); INSERT INTO b VALUES (2), (3), (3), (4);
SELECT x FROM a EXCEPT SELECT x FROM b ORDER BY x;
SELECT x FROM a INTERSECT SELECT x FROM b ORDER BY x;The first returns 1; the second returns 2 and 3.