sql:组合2个查询给出1个结果集

时间:2012-11-20 12:19:45

标签: mysql sql database oracle

在我必须执行2个查询的情况下,我想通过简单的一行查询来替换它。例如:

select col1, col2 from tableA where col3 = 'a';

这将返回(考虑)2行:

col1    col2

abc     abc.bcd
xyz     xyz.pqr

现在,在第二个表中,我们对查询1中的每一行进行了不同的查询:

   select col1 from tableB where col2 = 'abc';
   (AND)
   select col1 from tableB where col2 = 'xyz';

这将给出如下结果集:

 TableB
 col1    
 1111    
 2222   

如果问题不清楚请提及,我将尝试用更好的例子来阐述。

(虽然数据库供应商没有问题,我对oracle或mysql很满意。谢谢)。

5 个答案:

答案 0 :(得分:1)

你基本上只需要在这两个表之间进行连接:

SELECT b.col1, a.col1
FROM tablea a 
INNER JOIN tableb b ON a.col1 = b.col2
WHERE a.col3 = 'a'

答案 1 :(得分:0)

您可以制作一个类似的查询:

select col1 from tableB where col2 = 'abc' or col2 = 'xyz';

如果要检查大量字符串,则可以使用:

select col1 from tableB where col2 in ('abc','xyz','mno');

更新:您可以使用嵌套查询,例如:

select col1 from tableB where col2 in (select col1 from tableA where col3='a');

但请确保嵌套查询中的col1数据类型与col2之后的where数据类型匹配。

答案 2 :(得分:0)

试试这个:

select col1 
from tableB
where col2 in (select col1 
               from tableA 
               where col3='a')

答案 3 :(得分:0)

您可以将单个查询用作

select col1, col2 from tableB where col2 = 'abc' or col2='xyz'

答案 4 :(得分:0)

对我来说并不完全清楚,但我认为您正在寻找通常的加入表达式?

SELECT B.Col1,A.Col1 FROM TableA A.Col1 = B.Col2

上的内连接TableB B.

请参阅Join表达式。此示例适用于SQL Server和更新版本的Oracle。

相关问题