-3

我遇到了一种情况,我需要根据具有不同值的列连接两个表。

例如

  • Table1有列T1
  • Table2有列T2

  • T1有 100 行有值P

  • T2有 50 行有值N和 50 行有值P

我想将具有值的表与Table1具有值以及PTable2NP

它应该给我总共 100 条记录。

4

3 回答 3

1

尝试这个:

SELECT 
  t1.t1, 
  t2.t2
FROM Table1 t1
INNER JOIN Table2 t2 ON t2.t2 IN('N', 'P')
WHERE T1.t1 = 'p';
  • 谓词IN ('N', 'P')将从 table2 中获取 t2 的值,该值具有NP

  • WHERE子句将从值为 的 tabale1 中获取 t1 的值P,您可以将此谓词移动到JOIN条件中。

于 2012-12-28T11:41:25.403 回答
0

Across join对左表中的每一行重复右表中的每一行。然后,您可以在where子句中指定任何“不相关”的条件:

select  *
from    Table1 t1
cross join
        Table2 t2
where   t1.col1 = 'N'
        and t2.col1 in ('N', 'P')
于 2012-12-28T11:42:01.550 回答
0

In your scenario any join will act as a cross join since you have many duplicates in both tables (Table1 with 100 rows of 'P' and Table2 with 50 rows of 'P'),

select  t1.*,t2.*
from    Table1 t1
join    Table2 t2
where   t1.field1 = 'N'
        and t2.field1 IN ('N', 'P')

And your requirement to get only 100 rows is not possible. Because, first row of 'P' in table1 will get be joined with 50 rows of table2 with 'P' and so you will get 50 rows in output for each row of table1. And if you really want 100 rows then put a LIMIT OR TOP as a filter condition.

Hope this helps you!!!

于 2012-12-28T11:57:35.270 回答