Sql将多行合并到列中

时间:2011-08-24 15:23:54

标签: sql oracle

我有2张桌子

表A

A1 | A2
 1 | 2
 2 | 3
 3 | 4

表B

B1 | B2
1  | 3
1  | 5
4  | 3

A1,A2,B1和B2都是ID的

我希望仅当A.A1 = B.B1时才将表A加入表B.

Select A.A1, A.A2, B.B2 from A JOIN B ON A.A1 = B.B1

应该返回

A1 | A2 | B2
1  | 2  | 3
1  | 2  | 5

但我希望以这种格式获取数据,我希望最终结果为:

A1   | Col2
1    | 2
1    | 3
1    | 5

额外的问题:我怎么知道哪些栏目信息来了?

A1   | Col2 | Table
1    | 2    | A
1    | 3    | B
1    | 5    | B

请求帮助。

Edit1:联盟不会工作,我不想简单地堆叠两个表中的字段,我想在一个条件下加入数据,但由于A2和B2是相同类型的ID我想在一个单独的数据collumn,它将简化将来对结果的查询。

3 个答案:

答案 0 :(得分:2)

要将多个表格显示为单个表格,请使用UNION

SELECT A1 as Col1, A2 as Col2, 'A' as Col3 FROM table_A
UNION ALL
SELECT B1 as Col1, B2 as Col2, 'B' as Col3 FROM table_B

根据修订后的问题,添加where条件可提供您正在寻找的结果。根据提供的情况,我仍然没有看到任何需要加入的原因。

SELECT * FROM
   (SELECT A1, A2 as Col2, 'A' as "TABLE" FROM table_A
    UNION ALL
    SELECT B1, B2 as Col2, 'B' as "TABLE" FROM table_B)
WHERE A1 = 1;

答案 1 :(得分:0)

你的问题不是很清楚,但你想要的可能是它。

CREATE TABLE a(a1 INT, a2 INT);
CREATE TABLE b(b1 INT, b2 INT);

INSERT INTO a VALUES(1, 2);
INSERT INTO a VALUES(2, 3);
INSERT INTO a VALUES(3, 4);

INSERT INTO b VALUES(1, 3);
INSERT INTO b VALUES(1, 5);
INSERT INTO b VALUES(4, 3);

COMMIT;

SELECT a1 AS "1", a2 AS "2", 'A' AS "src" FROM a
UNION
SELECT a1, b2, 'B' FROM a, b WHERE a1 = b1;

1                      2                      src 
---------------------- ---------------------- --- 
1                      2                      A   
1                      3                      B   
1                      5                      B   
2                      3                      A   
3                      4                      A   

答案 2 :(得分:0)

这样的事情,可能:

SELECT
  u.*
FROM (
  SELECT A1, B1 AS Col2, 'A' AS SourceTable FROM A
  UNION ALL
  SELECT B1, B2 AS Col2, 'B' AS SourceTable FROM B
) u
  INNER JOIN (
    SELECT A1 FROM A
    INTERSECT
    SELECT B1 FROM B
  ) i ON u.A1 = i.A1