将具有不同列的表组合到单个查询中

时间:2017-05-24 07:08:22

标签: sql postgresql sqlalchemy

我正在编写一个网站,我想制作一个显示用户活动的时间表:他写的评论(在网站上的文章),他发布的消息(在论坛上)和[向上|向下]投票他是谁。

现在我有三个表(跳过非相关字段):

COMMENTS
id | author_id | article_id | timestamp

MESSAGES
id | author_id | thread_id | timestamp

VOTES
id | author_id | comment_id | message_id | type | timestamp

我想执行一个查询,如果author_id将返回结合来自COMMENTS的article_id字段,来自MESSAGES的thread_idcomment_id的结果的查询来自VOTES和公共message_id字段的typetimestamp字段,全部按时间戳排序。结果应该是这样的:

article_id | thread_id | comment_id | message_id | type | timestamp

我正在使用PostgreSQL,到目前为止我一直无法生成这种结果。

有人能指出我正确的方向吗?

修改

为了澄清我想要实现的目标,如果我在数据库中有以下数据:

COMMENTS
id | author_id | article_id | timestamp
 1 |         1 |         1  | 11:00:10
 2 |         1 |         2  | 11:00:20

MESSAGES
id | author_id | thread_id | timestamp
 3 |         1 |        20 | 12:00:10
 4 |         1 |        21 | 12:00:20

VOTES
id | author_id | comment_id | message_id | type | timestamp
 5 |         1 |          1 |            |    1 | 13:00:10
 6 |         1 |            |          3 |    2 | 13:00:20

然后结果应该是这样的:

article_id | thread_id | comment_id | message_id | type | timestamp
         1 |           |            |            |      | 11:00:10
         2 |           |            |            |      | 11:00:20
           |        20 |            |            |      | 12:00:10
           |        21 |            |            |      | 12:00:20
           |           |          1 |            |    1 | 13:00:10
           |           |            |          3 |    2 | 13:00:20

提前致谢。

2 个答案:

答案 0 :(得分:1)

我不知道您为什么需要此输出,但您可以尝试以下联合查询:

SELECT
    article_id, NULL, NULL, NULL, NULL, timestamp
FROM COMMENTS
WHERE author_id = 1
UNION ALL
SELECT
    NULL, thread_id, NULL, NULL, NULL, timestamp
FROM MESSAGES
WHERE author_id = 1
UNION ALL
SELECT
    NULL, NULL, comment_id, message_id, type, timestamp
FROM VOTES
WHERE author_id = 1
ORDER BY timestamp

答案 1 :(得分:0)

洗脱

select c.author_id ,article_id, thread_id , comment_id, message_id, type, c.timestamp
    FROM COMMENTS c
    LEFT JOIN MESSAGES m
        ON c.author_id = m.author_id and c.timestamp = m.timestamp
    LEFT JOIN VOTES v
        ON c.author_id = v.author_id and c.timestamp = v.timestamp
    where author_id=@author_id

如果时间戳不相同,那么试试这个

select c.author_id ,article_id, thread_id , comment_id, message_id, type, isnull(isnull(c.timestamp,m.timestamp),v.timestamp) as timestamp
    FROM COMMENTS c
    full JOIN MESSAGES m
        ON c.author_id = m.author_id 
    full JOIN VOTES v
        ON c.author_id = v.author_id 
    where author_id=@author_id