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

b4wnujal  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(349)

我正在尝试从现有表中获取行(按列: p_id , e_id , ts , data1 , data2 , data3 )到临时表(按索引) p_id , e_id , ts ),然后从临时表中选择特定行作为结果。然后终止临时表(因为createtemporary就是这么做的,对吧?)
我回顾了这两篇文章:
mysql中如何将数据合并到临时表中
在select语句中创建临时表,而不使用单独的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);
prdp8dxp

prdp8dxp1#

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;

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

u4dcyp6a

u4dcyp6a2#

如果你以后不打算用的话,为什么还要用临时table呢?
下一个就不行了?

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

如果我漏了什么,请纠正我

jyztefdp

jyztefdp3#

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

jtjikinw4#

您可以使用下面的查询,它将在表中给出愿望:

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;

不需要删除临时表,它会自动删除一个会话关闭。

相关问题