我有多个不同的查询,我想将结果存储到一个表中。此查询的结果可能具有不同的行数和列数。
e.g。 我有三个问题:
Q1。 select name,id from employee;
(结果有2列2行)
Q2。 select salary from emp_table
(结果有1列4行)
Q3。 select country_name,Country_id,count(id) from players group by country_name,Country_id
(结果有3列3行)
现在,我想将这些结果存储到一个表中,该表的结构如下:
Query_ID | col1 | col2 | col3
-------------------------------
在此表中,query_id是A1,A2,A3 ......
等查询的唯一ID当查询结果少于三列时,剩余列应填充为null(对于第一个查询,col3应为null,对于第二个查询,col2和col3应为null)。
期望的输出:
Query_ID | col1 | col2 | col3
----------
A1 | John | 1356 | NULL
A1 | Mathew | 1667 | NULL
A2 | 1500 | NULL | NULL
A2 | 2000 | NULL | NULL
A2 | 3000 | NULL | NULL
A2 | 3500 | NULL | NULL
A3 | US | 010 | 25
A3 | UK | 012 | 26
A3 | GER | 016 | 16
答案 0 :(得分:0)
您可以对字段使用别名,以便为不同的查询设置统一的结果集。
Q1 select name as col1,id as col2, '' as col3 from employee;
对于Q2 select salary as col1, '' as col2, '' as col3 from emp_table
对于Q3 select country_name as col1,Country_id as col2,count(id) as col3 from players group by country_name,Country_id
然后您可以使用insert语句来保存这些查询。例如:
INSERT INTO table (col1,col2,col3)
select name as col1,id as col2, '' as col3 from employee;
然后,您可以根据需要使用上述任何查询。
答案 1 :(得分:0)
您使用Union All
SELECT 'A1' AS Query_ID, name AS Col1, id AS Col2, '' AS Col3
FROM employee
UNION ALL
SELECT 'A2' AS Query_ID, salary AS Col1, '' AS Col2, '' AS Col3
FROM emp_table
UNION ALL
SELECT 'A2' AS Query_ID, country_name AS Col1, Country_id AS Col2, count(id) AS Col3
FROM players
GROUP BY country_name, Country_id
答案 2 :(得分:0)
insert into new_table (query_id,col1,col2,col3)
select 'A1' as QUERY_ID,name as col1,id as col2,'' as col3 from employee
union all
select 'A2' AS QUERY_ID,salary as col1,'' as col2,'' as col3 from emp_table
union all
select 'A3' AS QUERY_ID,country_name,Country_id,count(id) from players group by country_name,Country_id;
确保要获取的列的数据类型兼容。假设name列是varchar,你要获取的薪水就是这个失败的数字。