mysql dual表的用途及案例

    技术2022-07-12  84

    mysql文档中对于dual表的解释:

    You are allowed to specify DUAL as a dummy table name in situations where no tables are referenced: 你可以在没有表的情况下指定一个虚拟的表名 mysql> SELECT 1 + 1 FROM DUAL; -> 2 DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced. DUAL是为了方便那些要求所有SELECT语句都应该具有FROM和其他子句的人。MySQL可能会忽略该条款。如果没有引用表,MySQL不需要从DUAL。

    select 7*9 from dual; 计算器 SELECT SYSDATE() from dual 获取系统时间 ................

    案例 开发过程中,需要对数据进行excel展示或导出,并且需要各种类型的数据,这里提供一种通过dual表来实现 创建表teacher,插入数据

    CREATE TABLE `teacher` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, `age` int(11) DEFAULT NULL, `score` int(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `index_three_key` (`name`,`age`,`score`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COMMENT='老师'; INSERT INTO teacher(id,name,age,score) VALUES(1,'Alen',32,98),(2,'Aony',43,1), (3,'Dansy',53,78),(4,'Fulanke',25,65),(5,'Tom',32,54) SELECT '员工汇总' AS id, '' AS NAME, '' AS age, '' AS score FROM DUAL UNION ALL SELECT * FROM teacher UNION ALL SELECT '平均值' AS id, '' AS NAME, '' AS age, cast( AVG( score ) AS DECIMAL ( 10, 3 )) AS score FROM teacher UNION ALL SELECT '' AS id, '' AS NAME, '' AS age, '' AS score FROM DUAL UNION ALL SELECT '绩效' AS id, '' AS NAME, '' AS age, '' AS score FROM DUAL UNION ALL SELECT 'A(评分)' AS id, 'B(评分)' AS NAME, 'C(评分)' AS age, 'D(评分)' AS score FROM DUAL UNION ALL SELECT ( SELECT COUNT( score ) FROM teacher WHERE score >= 90 ) AS id, ( SELECT COUNT( score ) FROM teacher WHERE score >= 80 AND score < 90 ) AS NAME, ( SELECT COUNT( score ) FROM teacher WHERE score >= 60 AND score < 80 ) AS age, ( SELECT COUNT( score ) FROM teacher WHERE score < 60 ) AS score FROM DUAL
    Processed: 0.011, SQL: 9