Sql查询从3个表中获取结果

时间:2013-01-17 04:40:20

标签: sql

我有以下表格结构。需要从最近由added_date添加的所有表格中选择记录。

我正在尝试从最近由titlename, sourcename, description, addde_date添加的table1, table2, table3中抓取added_date

标题名称和来源名称存储在标题和源表中。

我在这些表上尝试了联合,但Table3包含了不同的列。

表1

    id   titleid   sourceid     text_content        added_date   -------
    1      15         20         XYzgff       10-10-2012:5:30pm
    2      10         5         gghghggg      10-11-2012:5:30pm

表2

    id   titleid   sourceid    description     added_date   -------
    1       6         8         fhjjjjjkk     11-04-2012:5:30pm 
    2      10         5         gghghggg      10-11-2012:5:30pm

表3

    id       url         Title     Description       added_date       -------------
    1       ggggg        fhhh        llllll         31-04-2012:5:30pm
    2       kkkkkk       ttttt       kkkkkk         10-11-2012:5:30pm  

标题表:

    titleid      title_name
      5            lgsfsgsf
      6            lkklgyy
      10           tyyiugj
      15          lklklklkl

来源表:

    sourceid      source_name
       5            jlkjljlj
       8            ghhhhhhh
       20           hhhhhhhf
       6            llllllll

1 个答案:

答案 0 :(得分:0)

您应该使用UNION。试试这个(未经测试):

SELECT t.title_name, s.source_name, t1.text_content, t1.added_date   
FROM Table1 t1
JOIN Title T 
   ON t1.TitleId = T.TitleId
JOIN Source S 
   ON t1.SourceId = S.SourceId
UNION
SELECT t.title_name, s.source_name, t2.description, t2.added_date   
FROM Table2 t2
JOIN Title T 
   ON t2.TitleId = T.TitleId
JOIN Source S 
   ON t2.SourceId = S.SourceId
UNION
SELECT t.title_name, s.source_name, t3.description, t3.added_date   
FROM Table3 t3
JOIN Title T 
   ON t3.TitleId = T.TitleId
JOIN Source S 
   ON t3.SourceId = S.SourceId

我刚刚意识到你的Table3中没有SourceId或TitleId。无法获得该信息,但您仍然可以这样做:

SELECT DISTINCT Title_Name, Source_Name, Text_Content, Added_Date
FROM 
(
   SELECT t.title_name, s.source_name, t1.text_content, t1.added_date   
   FROM Table1 t1
   JOIN Title T 
     ON t1.TitleId = T.TitleId
   JOIN Source S 
     ON t1.SourceId = S.SourceId
   UNION
   SELECT t.title_name, s.source_name, t2.description, t2.added_date   
   FROM Table2 t2
   JOIN Title T 
     ON t2.TitleId = T.TitleId
   JOIN Source S 
     ON t2.SourceId = S.SourceId
   UNION
   SELECT t3.title, 'Unknown', t3.description, t3.added_date   
   FROM Table3 t3
) t
ORDER BY added_date