author_id | author_name |
1 | Kimmy |
2 | Abel |
3 | Bill |
4 | Berton |
bo ok_id | author_id | start_date | end_date | |
9 | 1 | 2017-09-25 21:16:04 | 2017-09-25 21:16:06 | |
10 | 3 | |||
11 | 2 | 2017-09-25 21:21:46 | 2017-09-25 21:21:47 | |
12 | 1 | |||
13 | 8 |
order_id | book_id | price | order_date | |
1 | 9 | 0.2 | 2017-09-24 21:21:46 | |
2 | 9 | 0.6 | 2017-09-25 21:16:04 | |
3 | 11 | 0.1 | 2017-09-25 21:21:46 |
在以上表中执行ABC表关联
SELECT `authors`.*, `books`.book_id, `orders`.order_id, `orders`.price FROM `authors` LEFT JOIN `books` ON `authors`.author_id = `books`.author_id LEFT JOIN `orders` ON `books`.book_id = `orders`.book_id
#通过group by 分类,使用sum ,avg,count等函数求值
SELECT `authors`.*, sum(`orders`.price) FROM `authors` LEFT JOIN `books` ON `authors`.author_id = `books`.author_id LEFT JOIN `orders` ON `books`.book_id = `orders`.book_id GROUP BY `books`.book_id
#使用where条件,where不能用于选取列的AS别名判断,MYSQL的处理机制是先进行选取,再进行筛选
SELECT `authors`.*, `books`.book_id, `orders`.order_id, sum(`orders`.price) AS prices FROM `authors` LEFT JOIN `books` ON `authors`.author_id = `books`.author_id LEFT JOIN `orders` ON `books`.book_id = `orders`.book_id AND `orders`.order_date >= `books`.start_date AND `orders`.order_date <= `books`.end_date WHERE `orders`.price is not NULL GROUP BY `books`.book_id
使用having关键字,对于无法使用where字段的price进行统计
SELECT `authors`.*, `books`.book_id, sum(`orders`.price)AS prices FROM `authors` LEFT JOIN `books` ON `authors`.author_id = `books`.author_id LEFT JOIN `orders` ON `books`.book_id = `orders`.book_id GROUP BY `books`.book_id HAVING prices > 0.1