select 1 from dual


begin 2018年7月14日15:06:29

select 1 from dual

Oracle下的select 1 from dual

今天在看公司代碼的時候,發現有這一句SQL:

select 1 from dual

然后覺得有點奇怪,數據庫里面都沒有創建這個dual表,這個表是從何而來呢?然后Google了一波,理解了一下。

首先,公司用的是Oracle數據庫,關於Oracle數據庫中的dual表,官方文檔說明(The DUAL Table):

DUAL is a small table in the data dictionary that Oracle Database and user-written programs can reference to guarantee a known result. The dual table is useful when a value must be returned only once, for example, the current date and time. All database users have access to DUAL.

The DUAL table has one column called DUMMY and one row containing the value X.

DUAL是一個在數據字典里的很小的表,Oracle數據庫和用戶寫的程序可以引用它來保證一個已知的結果。當一個值(比如當前date和time)有且僅需返回一次的時候,這個dual表還是很管用的。所有數據庫用戶都可以訪問DUAL

DUAL表有一列,名叫DUMMY和有一行,值為X

Selecting from the DUAL Table

DUAL is a table automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X.

Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once. Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the value will be returned as many times as there are rows in the table.

DUAL是一個隨着Oracle數據庫創建數據字典時自動創建的表。雖然DUAL在用戶SYS模式下,但是還是可以被所有用戶訪問的。它有一列,DUMMY,定義為VARCHAR2(1),和包含一行數據,值為X

對於用SELECT計算一個常量表達式來說,從DUAL選擇是比較好用的。因為DUAL只有一行,所以常量只會返回一次。或者,你可以從任意一個表中選擇常量、偽列和表達式,但是這個值將返回多次,次數和表的行數一樣多。

我們可以在Oracle數據庫查詢:

SQL> select * from dual;
DUMMY
-----
X

好的,現在我們知道了dual這個表是長什么樣了,也知道為什么會用這個表了。划重點:當一個值必須返回,且只返回一次,可以從dual表選擇返回。

我看了一下項目代碼,這句SQL是傳給數據庫連接池驗證連接的,這樣就很合理了:不需要返回太多的值,但是有必須有返回,選擇從dual返回再正確不過了。

MySQL下的select 1 from dual

SELECT Syntax

SELECT can also be used to retrieve rows computed without reference to any table.
SELECT也可以在沒有引用任何表,用來檢索行。

For example:
比如:

mysql> SELECT 1 + 1;
    -> 2

You are permitted to specify DUAL as a dummy table name in situations where no tables are referenced:
在沒有引用表的情況下,你可以指定DUAL為一個虛擬表名。

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也不要求FROM DUAL

在MySQL中使用dual表並不總是對的:

mysql> select 1 from dual;
3013 - Unknown table ****.dual

其實MySQL就直接SELECT就行。

end 2018年7月14日17:36:24


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM