MySQL之多表查询练习

Posted Charles-MQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL之多表查询练习相关的知识,希望对你有一定的参考价值。

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

以上是关于MySQL之多表查询练习的主要内容,如果未能解决你的问题,请参考以下文章

MySQL之多表查询

mysql 之多表查询

MySQL之多表查询

mysql第四篇:数据操作之多表查询

MySQL之多表查询

MySQL之多表查询