将数据从表插入临时表,然后从临时表中选择特定行

问题描述 投票:0回答:4

我试图从现有表(p_ide_idtsdata1data2data3)获取行到临时表(由p_ide_idts索引),然后从该临时表中选择特定行结果是。然后终止临时表(因为这就是CREATE TEMPORARY所做的,对吧?)

我回顾了这两篇文章:

并得到了正确编写查询(我的查询不运行)的困惑。

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);
mysql sql temp-tables
4个回答
3
投票
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 ;

0
投票
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;

看起来你只需要删除第一组(),并在语句之间添加一个分号。


0
投票

你可以使用下面的查询,它会给表中的欲望:

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表,它会在一个会话关闭时自动丢弃。


-1
投票

如果您以后不计划使用临时表,为什么还需要临时表?

接下来不会做这个工作?

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';

如果我错过了什么,请纠正我

© www.soinside.com 2019 - 2024. All rights reserved.