SQL连接在一个表上具有不同的列

时间:2016-01-29 22:59:01

标签: sql oracle

也许我正在使用错误的单词进行搜索,因为我找不到答案elswhere,但我需要连接两个表,但要确保其中一个表的ID是不同的。如下所示:

SELECT B.COLUMN_A, B.COLUMN_B, B.COLUMN_C
FROM TABLE1 A
JOIN TABLE2 B
ON (Distinct) A.COLUMN_A = B.COLUMN_A;

来自A.COLUMN_A的{​​{1}}值必须为TABLE1

我已尝试过以下但不起作用:

DISTINCT

我一直在SELECT B.COLUMN_A, B.COLUMN_B, B.COLUMN_C FROM TABLE1 A JOIN (SELECT DISTINCT COLUMN_A FROM TABLE2) B ON A.COLUMN_A = B.COLUMN_A; 收到ORA-00904:无效的识别错误。如果我尝试使用B.COLUMN_C,那么我会收到ORA-00905:缺少关键字错误。

5 个答案:

答案 0 :(得分:0)

如果您不关心其他值,请使用group by

SELECT b.column_a, b.column_b, b.column_c
FROM table1 a
  JOIN (
    SELECT column_a, max(column_b) as column_b, max(column_c) as column_c
    FROM table2
    GROUP BY column_a
  ) b ON a.column_a = b.column_a

答案 1 :(得分:0)

使用ROW_NUMBERCOLUMN_A获得一行:

SELECT *
FROM table1 A
JOIN
 (
   SELECT *,
      ROW_NUMBER() OVER (PARTITION BY COLUMN_A ORDER BY COLUMN_A) AS rn
   FROM table2
   GROUP BY column_a
 ) B
ON A.column_a = B.column_a
AND B.rn = 1

答案 2 :(得分:0)

也许你需要这样的东西:

 select * from 
(
    select column_a,column_b,column_c
    from 
        (
            select  column_a,column_b,column_c, count(1) over (partition by column_a) as num
            from tableB
        )
    where num = 1
)tB
inner join tableA
using (column_a)

双嵌套不是必需的,但我希望它使查询更具可读性

答案 3 :(得分:0)

如果你需要col_a,col_b,col_c并且想要确保col_a永远不会重复和col_b,col_c值不是密切关系,那么:

SELECT col_a, col_b, col_c 
FROM table2 
WHERE rowid in ( SELECT min(rowid) 
                 FROM table2 A , table1 B )
                 WHERE B.col_a = A.col_a 
                 GROUP BY A.col_a )

在上面,您选择Table1中也存在的一个不同的Table2行。然后使用该行的ID,您可以选择所有三列。

答案 4 :(得分:0)

您没有从TABLE1中选择任何列,因此您加入(不同的)TABLE1记录实际上只是一个半连接,最容易表达为:

SELECT B.COLUMN_A, B.COLUMN_B, B.COLUMN_C
FROM TABLE2 B
WHERE EXISTS ( SELECT 'at least one row in table1' 
               FROM   TABLE1 A
               WHERE  A.COLUMN_A = B.COLUMN_A );