我如何加入(合并?)几个表?

时间:2009-03-30 11:36:20

标签: sql sql-server join merge

我有三张桌子

AUTHOR_TABLE
-------------
AUTHOR_ID (PK)   AUTHOR_NAME   
1                me
2                you 

ARTICLE_AUTHOR_TABLE
-------------
AUTHOR_ID  ARTICLE_ID  
1          100
2          101


EVENT_AUTHOR_TABLE
------------------------------------------
AUTHOR_ID   EVENT_ID  
1           200
1           201

我想要的只是

RESULTS
-----------------------------------------
AUTHOR_ID AUTHOR_NAME SOURCE_TABLE ID
1         me          article      100
2         you         article      101
1         me          event        200
1         me          event        201 

/* where SOURCE_TABLE would be either "EVENT" or "ARTICLE" */

编辑我真的不想要这个

RESULTS
-----------------------------------------
AUTHOR_ID AUTHOR_NAME EVENT_ID ARTICLE_ID
1         me          NULL         100
2         you         NULL         101
1         me          200         NULL
1         me          201         NULL

任何指针都表示赞赏。

感谢

3 个答案:

答案 0 :(得分:3)

SELECT
  at.author_id,
  at.author_name,
  'article' AS source_table,
  aat.id
FROM
  author_table at
  JOIN article_author_table aat
    ON at.author_id = aat.author_id

UNION ALL

SELECT
  at.author_id,
  at.author_name,
  'event' AS source_table,
  eat.id
FROM
  author_table at
  JOIN event_author_table eat
    ON at.author_id = eat.author_id

答案 1 :(得分:1)

SELECT A.AUTHOR_ID, A.AUTHOR_NAME, EA.EVENT_ID, AA.ARTICLE_ID
FROM AUTHOR_TABLE AS A
    LEFT JOIN ARTICLE_AUTHOR_TABLE AS AA ON AA.AUTHOR_ID = A.AUTHOR_ID
    LEFT JOIN EVENT_AUTHOR_TALBE AS EA ON EA.AUTHOR_ID = A.AUTHOR_ID

答案 2 :(得分:0)

由于这是家庭作业,我猜你正在使用MySQL,read this documentation on the UNION syntax。你在做什么基本上是从类似的数据库中做两个(或更多)查询,并在一个查询中得到结果。

请注意,生成的列必须相同。

您还可以创建变量以显示您正在呼叫的表格。

SELECT AUTHOR_ID, AUTHOR_NAME, `AUTHOR_TABLE` AS SOURCE_TABLE, ID FROM AUTHOR_TABLE

您将对所有联盟执行此操作,但更改表名。