MySQL - 派生表



MySQL 派生表

派生表与其名称所描述的非常相似:它们是从另一个 MySQL 数据库表(主表)派生的表。换句话说,派生表是从作为子查询提供给另一个主表的 SELECT 语句的 SELECT 语句获得的虚拟结果集。

此表类似于临时表。但与临时表不同,您无需单独创建派生表;其中的记录是使用子查询从主表中检索的。因此,类似于实际的数据库表,派生表也可以显示为计算、聚合函数等的结果集。

语法

以下是显示 MySQL 中派生表的语法:-

SELECT column_name(s) FROM (subquery) AS derived_table_name;

示例

让我们看一个简单的示例,演示如何在 MySQL 中显示派生表。在以下查询中,我们正在创建一个新表CUSTOMERS -

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

以下查询将 7 条记录插入到上面创建的表中:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

要检索 CUSTOMERS 表的记录,请执行以下查询:

SELECT * FROM CUSTOMERS;

以下是 CUSTOMERS 表中存在的记录:

ID 姓名 年龄 地址 工资
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

现在,我们使用以下查询从此 CUSTOMERS 表中检索派生表

SELECT ID, NAME, SALARY FROM (SELECT * FROM CUSTOMERS) AS DERIVED_CUSTOMERS;

因此,派生表 DERIVED_CUSTOMERS 获得,其属性为 ID、NAME 和 SALARY。

ID 姓名 工资
1 Ramesh 2000.00
2 Khilan 1500.00
3 Kaushik 2000.00
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00

使用 WHERE 子句

我们还可以使用 WHERE 子句过滤派生表中的记录(或行)。以下是它的语法:-

SELECT column_name(s) FROM (subquery) AS derived_table_name WHERE [condition];

示例

在以下查询中,我们从最初创建的 CUSTOMERS 表中检索派生表。我们通过使用WHERE子句过滤其中的行来执行此操作:

SELECT ID, NAME, SALARY FROM (SELECT * FROM CUSTOMERS) AS DERIVED_CUSTOMERS 
WHERE DERIVED_CUSTOMERS.SALARY > 5000.00;

执行上面的查询将产生以下输出:

ID 姓名 工资
4 Chaitali 6500.00
5 Hardik 8500.00
7 Muffy 10000.00

在派生表中为列设置别名

在派生表中,不仅可以表名,还可以显示内容时为列名设置别名。以下是语法:-

SELECT column_name(s) AS alias_name(s) FROM (subquery) AS derived_table_name;

示例

在下面的示例中,我们使用以下查询显示来自 CUSTOMERS 表的派生表,并带有使用别名的列:

SELECT ID AS DERIVED_ID, NAME AS DERIVED_NAME, SALARY AS DERIVED_SALARY 
FROM (SELECT * FROM CUSTOMERS) AS DERIVED_CUSTOMERS;

输出

执行上面的查询将产生以下输出:

DERIVED_ID DERIVED_NAME DERIVED_SALARY
1 Ramesh 2000.00
2 Khilan 1500.00
3 Kaushik 2000.00
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00

将聚合函数显示为派生表

我们还可以将主表记录上执行的聚合函数或计算的结果显示为派生表。

以下是将聚合函数显示为派生表的语法:-

SELECT function_name() FROM (subquery) AS derived_table_name;

示例

在以下查询中,我们使用聚合 SUM() 函数计算 CUSTOMERS 表中的总工资:

SELECT SUM(SALARY) FROM (SELECT SALARY FROM CUSTOMERS) AS DERIVED_CUSTOMERS;

输出

执行上面的查询将产生以下输出:

SUM(SALARY)
35000.00

示例

在以下查询中,我们使用聚合 AVG() 函数计算 CUSTOMERS 表中客户的平均工资。

SELECT AVG(DERIVED_SUM) AS AVERAGE_SALARY 
FROM (SELECT SUM(SALARY) AS DERIVED_SUM FROM CUSTOMERS) AS DERIVED_CUSTOMERS;

输出

执行上面的查询将产生以下输出:

AVERAGE_SALARY
35000.000000

使用客户端程序派生表

除了使用 MySQL 查询从另一个数据库表(主表)派生表之外,我们还可以使用 Node.js、PHP、Java 和 Python 等客户端程序来获得相同的结果。

语法

以下是各种编程语言中此操作的语法:-

要通过 PHP 程序从另一个数据库表派生表,我们需要使用mysqli函数query()执行SELECT语句,如下所示:

$sql="SELECT col_1, col_2 FROM table_name WHERE col_name IN (SELECT col_name FROM table_name)";
$mysqli->query($sql);

要通过 Node.js 程序从另一个数据库表派生表,我们需要使用mysql2库的query()函数执行SELECT语句,如下所示:

sql ="SELECT column_name(s) FROM (subquery) AS derived_table_name";
con.query(sql);

要通过 Node.js 程序从另一个数据库表派生表,我们需要使用JDBC函数executeUpdate()执行SELECT语句,如下所示:

String sql="SELECT col_1, col_2 FROM table_name WHERE col_name IN (SELECT col_name FROM table_name)";
statement.executeQuery(sql);

要通过 Node.js 程序从另一个数据库表派生表,我们需要使用 MySQLConnector/Pythonexecute()函数执行SELECT语句,如下所示:

sql="SELECT col_1, col_2 FROM table_name WHERE col_name IN (SELECT col_name FROM table_name)";
cursorObj.execute(sql);

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf('Connected successfully.
'); //derived table (sub query) $sql = "SELECT tutorial_title, tutorial_author FROM tutorials_table WHERE tutorial_id IN (SELECT tutorial_id FROM tutorials_table);"; if ($result = $mysqli->query("$sql")) { printf("Derived table query worked successfully!.
"); while ($res = mysqli_fetch_array($result)) { print_r($res); } } if ($mysqli->errno) { printf("Derived table could not be worked!.
", $mysqli->error); } $mysqli->close();

输出

获得的输出如下:

Derived table query worked successfully!
Array
(
    [0] => MySQL
    [tutorial_title] => MySQL
    [1] => Aman kumar
    [tutorial_author] => Aman kumar
)
Array
(
    [0] => Python
    [tutorial_title] => Python
    [1] => Sarika Singh
    [tutorial_author] => Sarika Singh
)

var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  sql = "USE TUTORIALS"
  con.query(sql);

  sql = "CREATE TABLE SAMPLE(ID INT NOT NULL,NAME VARCHAR (20) NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(25),SALARY DECIMAL(18, 2),PRIMARY KEY (ID));"
  con.query(sql);

  sql = "INSERT INTO SAMPLE VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),(2, 'Khilan', 25, 'Delhi', 1500.00 ),(3, 'kaushik', 23, 'Kota', 2000.00 ),(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),(5, 'Hardik', 27, 'Bhopal', 8500.00 ),(6, 'Komal', 22, 'MP', 4500.00 ),(7, 'Muffy', 24, 'Indore', 10000.00 );"
  con.query(sql);

  //retrieving a derived table
  sql = "SELECT ID, NAME, SALARY FROM (SELECT * FROM SAMPLE) AS DERIVED_SAMPLE;"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log(result);
  });
});

输出

产生的输出如下:

Connected!
--------------------------
[
  { ID: 1, NAME: 'Ramesh', SALARY: '2000.00' },
  { ID: 2, NAME: 'Khilan', SALARY: '1500.00' },
  { ID: 3, NAME: 'kaushik', SALARY: '2000.00' },
  { ID: 4, NAME: 'Chaitali', SALARY: '6500.00' },
  { ID: 5, NAME: 'Hardik', SALARY: '8500.00' },
  { ID: 6, NAME: 'Komal', SALARY: '4500.00' },
  { ID: 7, NAME: 'Muffy', SALARY: '10000.00' }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DerivedTable {public static void main(String[] args) {
    String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
    String username = "root";
    String password = "password";
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);
        Statement statement = connection.createStatement();
        System.out.println("Connected successfully...!");

        //Lock table....
        String sql = "SELECT tutorial_title, tutorial_author FROM tutorials_tbl WHERE tutorial_id IN (SELECT tutorial_id FROM tutorials_tbl)";
        ResultSet resultSet = statement.executeQuery(sql);
        System.out.println("Table derived successfully...!");
        while (resultSet.next()) {
            System.out.print(resultSet.getString(1)+ " " +resultSet.getString(2));
            System.out.println();
        }

        connection.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
}

输出

获得的输出如下所示:

Connected successfully...!
Table derived successfully...!
Learn PHP John Paul
Learn MySQL Abdul S
JAVA Tutorial Sanjay
Python Tutorial Sasha Lee
Hadoop Tutorial Chris Welsh
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
table_name = 'tutorials_tbl'
# Main query with a derived table (subquery)
main_query = """
SELECT d.tutorial_id, d.tutorial_title, d.tutorial_author, d.submission_date
FROM (
    SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
    FROM tutorials_tbl
    WHERE submission_date >= '2023-01-01'
) AS d
WHERE d.tutorial_author LIKE '%Paul%'
"""
cursorObj = connection.cursor()
cursorObj.execute(main_query)
result = cursorObj.fetchall()
print("Derived Table Result:")
for row in result:
    print(f"| {row[0]:<11} | {row[1]:<15} | {row[2]:<15} | {row[3]:<15} |")
cursorObj.close()
connection.close()

输出

以下是上述代码的输出:

Derived Table Result:
| 1           | Learn PHP       | John Paul       | <15 |

广告