首页 > 解决方案 > 如何定义表名并进行多表选择

问题描述

我需要在 SQL 的查询中使用多个表选择。但是如何引用查询中选择的表呢?

例如:(伪代码)

create table C as
select distinct id, product_code
from (
   select distinct id, product_code 
   from A where dt = '2019-06-01'
) 
inner join B on (select distinct id, product_code 
                 from A where dt='2019-06-01').id = B.id;

上面的代码可能是错误的,但关键是表 A 不能直接使用,因为它太大了,必须指定 dt 是某个特定值。(所以我需要从 A 中选择两次以上)。我需要将较小的 A' 与其他表 B 进行内部连接。

例如,是否有可能“定义”表 A_ = select distinct blabla...from A ... 然后在查询中将 A_ 与 B 连接?

谢谢,

标签: sql

解决方案


您只需要一个表别名:

select distinct id, product_code
from (select distinct id, product_code
      from table_A
      where dt = '2019-06-01'
     ) a inner join
     table_B b
     on a.id = B.id;

推荐阅读