【发布时间】:2014-10-28 06:29:00
【问题描述】:
我有两个子查询,我想从中选择两个不同的列,但我不知道如何操作。试了很久。
换句话说,我需要这样做:
select distinct A, B
from (select * from selectstatement 1, selectstatement 2);
我有的是这个。
我有两张表,table1 和 table2,每列都有 int 类型的三列。
我有:
selectstatement 1:
select *
from table1, table2;
selectstatement 2:
select distinct table1.A, table1.B, table2.A, table2.B
from table1, table2
where (table1.A > table1.B and table2.A > table2.B)
or (table1.B > table1.A and table2.B > table2.A);
我现在的问题是从这两个 select 语句中选择列 A 和 B,例如 select distinct A, B from (select * from selectstatement 1, selectstatement 2);
但我尝试过的一切都没有奏效。
这不起作用:
select distinct P.A, P.B, T.A, T.B
from ( select distinct table1.A, table1.B, table2.A, table2.B
from table1, table2
where (table1.A > table1.B and table2.A > table2.B)
or (table1.B > table1.A and table2.B > table2.A)) as P,
(select * from table1, table2) as T;
但是如果我应该像“select distinct A, B from (select * from selectstatement 1, selectstatement 2);”那样做这也是错误的,不是吗?
【问题讨论】:
-
查看表格别名
-
查询 2 看起来不错。您选择有问题的四列。但是,您要在查询 1 中选择哪些列?还有 P.A、P.B、T.A、T.B?您正在那里进行交叉连接,因此您可以获得所有可用的组合。查询 2 中不能有任何组合不在查询 1 中。所以显然你想要不同的东西。但是什么?您说的是 两个 不同的列,但您选择的是 四个。建议:试着解释结果集应该是什么样的,就好像你对 SQL 一无所知。不要谈论连接和组合查询。只需描述结果表即可。
-
@ThorstenKettner:很好的建议。我会更进一步,不要描述结果表,而只是描述您正在寻找的结果。
标签: sql select relational-algebra