初识Mysql(part18)--我需要知道的4个关于联结的小知识点

学习笔记,以代码和例子堆砌而成,方便查阅。
参考书籍:《Mysql必知必会》等
要点:表别名,自链接,外连接,聚合函数与联结


此Blog会用到下面2个表.

temp_product表:

# pr_id, pro_name, price
'1001', 'Apple', '3'
'1002', 'Pen', '50'
'1003', 'Book', '35'
'1004', 'Hamburger', '10'
'1005', 'Toy', '15'
'1006', 'Fish', '20'

temp_shop表:

# id, pr_id, sale_num, customer
'1', '1001', '10', 'Ada'
'2', '1001', '4', 'Peter'
'3', '1001', '2', 'Jack'
'4', '1002', '10', 'Black'
'5', '1002', '2', 'Tim'
'6', '1003', '5', 'Kit'
'7', '1004', '2', 'Bunny'
'8', '1005', '100', 'Horde'
'9', '1005', '5', 'Mansion'
'10', '1000', '1', 'Rift'

给表起别名


我们给temp_product 起别名为 p, temp_shop 起别名为 s

SELECT p.pro_name, s.customer 
FROM temp_product AS p,temp_shop AS s 
WHERE p.pr_id=s.pr_id;

查询结果:

# pro_name, customer
'Apple', 'Ada'
'Apple', 'Peter'
'Apple', 'Jack'
'Pen', 'Black'
'Pen', 'Tim'
'Book', 'Kit'
'Hamburger', 'Bunny'
'Toy', 'Horde'
'Toy', 'Mansion'

使用表别名不仅可以缩短SQL语句,而且允许在单条SELECT语句中多次使用相同的表。


自联结


我们想查找temp_shop 表中客户Jack买的商品,总共卖出去多少件

SELECT s1.pr_id, SUM(s1.sale_num) AS total 
FROM temp_shop AS s1,temp_shop AS s2 
WHERE s1.pr_id=s2.pr_id AND s2.customer='Jack';

查询结果:

# pr_id, total
'1001', '16'

外部链接


SELECT p.pr_id, p.pro_name, s.customer 
FROM temp_product AS p LEFT OUTER JOIN temp_shop AS s 
ON p.pr_id=s.pr_id;

查询结果:

# pr_id, pro_name, customer
'1001', 'Apple', 'Ada'
'1001', 'Apple', 'Peter'
'1001', 'Apple', 'Jack'
'1002', 'Pen', 'Black'
'1002', 'Pen', 'Tim'
'1003', 'Book', 'Kit'
'1004', 'Hamburger', 'Bunny'
'1005', 'Toy', 'Horde'
'1005', 'Toy', 'Mansion'
'1006', 'Fish', NULL

外部联结分为左联结(LEFT OUTER JOIN)和右联结(RIGHT OUTER JOIN)


使用带聚集函数的联结


SELECT p.pr_id, p.pro_name,COUNT(*) AS shoping_count
FROM temp_product AS p RIGHT OUTER JOIN temp_shop AS s 
ON p.pr_id=s.pr_id
GROUP BY s.pr_id;

查询结果:

# pr_id, pro_name, shoping_count
NULL, NULL, '1'
'1001', 'Apple', '3'
'1002', 'Pen', '2'
'1003', 'Book', '1'
'1004', 'Hamburger', '1'
'1005', 'Toy', '2'
上一篇:【JAVA】1002 A+B for Polynomials (25分) PAT甲级 PAT (Advanced Level) Practice


下一篇:正负数取反的结果和规律