将多个查询的输出合并为一个

时间:2011-02-03 19:15:34

标签: mysql

1.select col1,col2 from table1 where condition1=<<value1>>
UNION ALL 
select col1,col2 from table2 condition1=<<value2>>;

2. `select col1 from table3;`

3. I need to write the 3rd query where i need the output of col1,col2 from table1 based on the col1 (sort based on col1 from table3).

我可以这样做

create table as temp_table as
select col1,col2 from table1 where condition1=<<value1>>
UNION ALL 
select col1,col2 from table2 condition1=<<value2>>;

SELECT t1.col1,t1.col2
FROM temp_table t1
LEFT OUTER JOIN table3 t2 ON t1.col2=t2.col2
order by t2.col1;

我想在一个查询中(在mysql中)&amp;不使用临时表。

有什么想法?感谢。

3 个答案:

答案 0 :(得分:3)

您可以将联合结果用作子选择。

答案 1 :(得分:2)

查看subqueries。它们有点像临时表,只在查询运行时才存在。

答案 2 :(得分:1)

Select T.A, T.B from

(select col1 as A,col2 as B from table1 where condition1=<<value1>>
UNION ALL 
select col1,col2 from table2 condition1=<<value2>>) as T,
table3 as T2
where T.A = T2.col1

order by t2.col1