将数据从表插入临时表,然后从临时表中选择特定行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数据从表插入临时表,然后从临时表中选择特定行相关的知识,希望对你有一定的参考价值。
我试图从现有表(p_id
,e_id
,ts
,data1
,data2
,data3
)获取行到临时表(由p_id
,e_id
,ts
索引),然后从该临时表中选择特定行结果是。然后终止临时表(因为这就是CREATE TEMPORARY所做的,对吧?)
我回顾了这两篇文章:
- How to combine data into a temporary table in Mysql
- Create a temporary table in a SELECT statement without a separate CREATE TABLE
并得到了正确编写查询(我的查询不运行)的困惑。
CREATE TEMPORARY TABLE IF NOT EXISTS
pet_temp ( INDEX(p_id, e_id, ts) )
AS (
SELECT p_id, e_id, ts, data1, data2, data3
FROM processes_history
WHERE e_id=4362 AND ts BETWEEN '2017-03-01' AND '2017-04-01'
) SELECT p_id, e_id, ts, data1, data2, data3 FROM pet_temp WHERE p_id IN (11,22,33,44,55,66,77,88,99);
答案
CREATE TEMPORARY TABLE IF NOT EXISTS
pet_temp ( INDEX(p_id, e_id, ts) )
AS (
SELECT p_id, e_id, ts, data1, data2, data3
FROM processes_history
WHERE e_id=4362 AND ts BETWEEN '2017-03-01' AND '2017-04-01'
) ;
SELECT p_id, e_id, ts, data1, data2, data3 FROM pet_temp WHERE p_id IN (11,22,33,44,55,66,77,88,99);
Drop temporary table if exists pet_temp ;
另一答案
CREATE TEMPORARY TABLE IF NOT EXISTS
pet_temp ( INDEX(p_id, e_id, ts) )
AS
SELECT p_id, e_id, ts, data1, data2, data3
FROM processes_history
WHERE e_id=4362 AND ts BETWEEN '2017-03-01' AND '2017-04-01';
SELECT p_id, e_id, ts, data1, data2, data3 FROM pet_temp WHERE p_id IN (11,22,33,44,55,66,77,88,99);
DROP TEMPORARY TABLE IF EXISTS pet_temp;
看起来你只需要删除第一组(),并在语句之间添加一个分号。
另一答案
你可以使用下面的查询,它会给表中的欲望:
CREATE TEMPORARY TABLE IF NOT EXISTS pet_temp (INDEX(p_id, e_id, ts))
SELECT p_id, e_id, ts, data1, data2, data3
FROM (
SELECT p_id, e_id, ts, data1, data2, data3
FROM processes_history
WHERE e_id=4362 AND ts BETWEEN '2017-03-01' AND '2017-04-01'
) x
WHERE p_id IN (11,22,33,44,55,66,77,88,99);
SELECT * FROM pet_temp;
不需要删除pet_temp表,它会在一个会话关闭时自动丢弃。
另一答案
如果您以后不计划使用临时表,为什么还需要临时表?
接下来不会做这个工作?
SELECT p_id, e_id, ts, data1, data2, data3 FROM processes_history WHERE e_id=4362 AND p_id IN (11,22,33,44,55,66,77,88,99) AND ts BETWEEN '2017-03-01' AND '2017-04-01';
如果我错过了什么,请纠正我
以上是关于将数据从表插入临时表,然后从临时表中选择特定行的主要内容,如果未能解决你的问题,请参考以下文章