0

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

我正在尝试titlename, sourcename, description, addde_datetable1, 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
4

1 回答 1

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
于 2013-01-17T04:46:22.907 回答