在 SQL 中,你可以使用
CREATE TABLE
语句来创建一个临时表,并使用
SELECT INTO
语句将查询结果插入到临时表中。
例如,假设你有一张名为
customers
的表,包含
customer_id
、
first_name
和
last_name
列,你可以执行以下操作来创建一个临时表并将查询结果插入到该临时表中:
CREATE TEMPORARY TABLE temp_customers (customer_id INT, first_name VARCHAR(50), last_name VARCHAR(50));
SELECT customer_id, first_name, last_name
INTO temp_customers
FROM customers
WHERE last_name = 'Smith';
在上面的示例中,我们首先使用 CREATE TEMPORARY TABLE 语句创建了一个名为 temp_customers 的临时表,并定义了三个列:customer_id、first_name 和 last_name。然后,我们使用 SELECT INTO 语句从 customers 表中选择所有 last_name 为 'Smith' 的行,并将结果插入到 temp_customers 表中。
请注意,临时表仅在当前会话有效,当会话结束时会自动删除。如果你希望保留临时表,可以使用 CREATE TABLE 语句将其转换为永久表。