20

我试图实现的是创建一个由几个子查询组成的复杂查询。这个想法是让业务人员每周运行一次以提取报告数据。

效果类似于下面的查询,其中来自许多表的所有数据都显示在一个结果中。

select * from table1, table2, table3

所以我需要类似的东西,但它不起作用。

select 
    (select * from   table1 where ...... ) as table1,
    (select * from   table2 where....... ) as table2

手动,我可以单独运行子查询,然后手动将结果附加到一个大的 Excel 表中。但我想让业务人员更容易做到这一点,并尽量减少错误。

这在 MySQL 中可能吗?

这样做的原因是我正在将旧的 Oracle PIVOT SQL 语句转换为 MySQL 等价语句,并且子查询非常复杂。

如果需要,我可以提供 Oracle SQL。

一如既往地非常感谢。

4

3 回答 3

31

经过一番折腾:

select * from
    (select * from   table1 where survey_user_id=4 ) as T1
    ,
    (select * from   table2 where survey_field_type_id=100 ) as T2
    ,
    (select * from table3  )  as T3
于 2013-03-06T21:04:38.477 回答
12

如果我理解正确,你只需要 UNION :D

(SELECT column1 AS name1, column2 AS name2 FROM table1 WHERE ...... )
UNION
(SELECT column3 AS name1, column4 AS name2 FROM table2 WHERE ...... )
UNION
....

正如评论中提到的,列需要具有相同的名称(您可以为其使用别名)并保持相同的顺序。

于 2013-03-06T21:05:49.837 回答
1
select main.*,
(select col from tbl1 where tbl1.id=main.id) as col1,
(select col from tbl2 where tbl2.id=main.id) as col2,
(select col from tbl3 where tbl3.id=main.id) as col3
from master as main
于 2017-07-19T04:28:59.647 回答