第一次接触dual表是在项目中看到别人写的,眼前一亮,又是发现新大陆的感觉,这样就有这篇博客诞生了。
自行百度一波,发现并不只有MySQL中有dual表。
一、Oracle中的dual表
ORACLE关于DUAL表不同寻常特性的解释:
There is internalized code that makes this happen. Code checks that ensure that a table scan of SYS.DUAL only returns one row. Svrmgrl behaviour is incorrect but this is now an obsolete product. The base issue you should always remember and keep is: DUAL table should always have 1 ROW. Dual is a normal table with one dummy column of varchar2(1). This is basically used from several applications as a pseudo table for getting results from a select statement that use functions like sysdate or other prebuilt or application functions. If DUAL has no rows at all some applications (that use DUAL) may fail with NO_DATA_FOUND exception. If DUAL has more than 1 row then applications (that use DUAL) may fail with TOO_MANY_ROWS exception. So DUAL should ALWAYS have 1 and only 1 row.
其实dual表主要就是Oracle在用,因为在Oracle中要满足select from 的结构。
DUAL是Oracle与数据字典一起自动创建的一个表,它只有一列:DUMMY,其数据类型为:VARCHAR2(1)。DUAL中只有一行数据:‘X’。DUAL属于SYS模式,但所有用户都可以使用DUAL名称访问它。用SELECT计算常量表达式、伪列等值时常用该表,因为它只返回一行数据,而使用其它表时可能返回多个数据行。
DUAL是一个Oracle内部表,不论我们做什么操作(不要删除记录)它都只有一条记录,上面插入了一条之后,他仍然只有1条记录,所以很多取系统时间,计算,等只要选择一条记录,而且记录内容与表内容无关的操作,我们都喜欢使用这个表。虚表(dual)是oracle提供的最小的工作表,它仅包含一行一列。对于虚表(dual)来说,其中的列往往是不相关的或无关紧要的。
实例:
(1)查看当前用户,可以在 SQL Plus中执行下面语句
select user from dual;
(2)用来调用系统函数
select to_char(SYSDATE,'yyyy-mm-dd hh24:mi:ss') from dual;--获得当前系统时间
select sys_context('userenv','terminal') from dual;--获得主机名
select sys_context('userenv','language') from dual;--获得当前locale
select DBMS_RANDOM.random from dual;--获得一个随机数
(3)可以用做计算器
select 7*9*10-10 from dual;
(4)查看系统时间
select sysdate from dual;
以上参考自:
https://blog.csdn.net/sinat_27143551/article/details/50269051
二、MySQL中的dual表
MySQL文档中对于dual表的解释:
You are allowed to specify DUAL as a dummy table name in situations where no tables are referenced:
SELECT 1+1 AS SUM FROM DUAL;
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.
由此看来MySQL中不是必须要满足select from结构,他的存在是为了给有这个要求的人使用,相当于一个摆设。
三、Oracle和MySQL中的dual对比
我们用实例来对比看区别:
select * from dual;
//MySQL报错: 1096 - No tables used
//Oracle返回“DUMMY”,其值为“X”, 行为和只有一行记录的普通表是一样的!
select express [from dual];
//MySQL中select 1+1;和select 1+1 from dual;作用相同。
//Oracle中必须加上from dual,不然报错:ORA-00923: FROM keyword not found where expected
select express from dual where 0=2;
//mysq 和 oracle的行为一致:该句就如同你认为的正常表那样——会先计算where的条件,再行计算express;这里的where条件会决定expres是否会返回!
select 1 + 1 from dual where 0 = 2;
//此时无论是Oracle还是MySQL都不可以省略from dual。
SQL server中是否有dual表呢???
SQL Server中没有DUAL,要什bai么就直接SELECT什么。
越大气越成功,越努力越幸运!