CTE定义:一个公共表表达式(common table expression)是一个命名的临时结果集,它在一条单独的语句中有效,可以在语句中被引用多次。
CTE基本语法:
WITH cte1 [(col_name [, col_name] ...)] AS (SELECT a, b FROM table1), cte2 [(col_name [, col_name] ...)] AS (SELECT c, d FROM table2) SELECT b, d FROM cte1 JOIN cte2 WHERE cte1.a = cte2.c;
CTE好处:
- 可以在一条语句中被引用多次。
- 可以递归引用(自引用)。
- 可以相互引用。
- 可读性好。
参考:WITH Syntax (Common Table Expressions)
----------------------------------------------------------------------------------------------------------------------------
备注:cte只能在mysql8.0及以上版本中使用。
测试数据表sql:books.sql
-- MySQL dump 10.13 Distrib 5.7.23, for linux-glibc2.12 (x86_64) -- -- Host: localhost Database: mydb -- ------------------------------------------------------ -- Server version 5.7.23-log /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `books` -- DROP TABLE IF EXISTS `books`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `books` ( `bno` varchar(32) DEFAULT NULL COMMENT '书号', `bname` varchar(64) DEFAULT NULL COMMENT '书名', `author` varchar(32) DEFAULT NULL COMMENT '作者', `price` double DEFAULT NULL COMMENT '单价' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `books` -- LOCK TABLES `books` WRITE; /*!40000 ALTER TABLE `books` DISABLE KEYS */; INSERT INTO `books` VALUES ('1001','definitive sql','wanger',61),('1002','java programming','wanger',45),('1003','shell programming','wanger',28),('1004','scala programming','lisi',32),('1005','c programming','lisi',66); /*!40000 ALTER TABLE `books` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-11-06 18:29:35
在mysql命令行中导入数据:mysql> source /path/books.sql;
mysql> with temp(booknum) as (select count(*) from books) select author,count(author)/(select booknum from temp) from books group by author;
输出如下: