有没有办法合并这两个表?

时间:2017-07-06 20:41:49

标签: sql postgresql database-design normalization database-normalization

我有两张桌子:

question_likes:

question_id references question(id)
user_id references users(id)
primary key (user_id, question_id)


answer_likes:

answer_id references answers(id)
user_id references users(id)
primary key (user_id, answer_id)

一位同事建议我可以在Postgres中使用继承将这些合并到一个表中。

有没有办法设计这个要求?

2 个答案:

答案 0 :(得分:1)

嗯,你不需要我相信。您可以在表之间执行JOIN并显示如下所示的必填字段。或者,使用以下SQL语句创建视图。

select q.question_id,
q.user_id,
a.answer_id 
from  question_likes q
join answer_likes a on a.user_id = q.user_id;

(或)klin评论中建议的full outer join

from  question_likes
full join answer_likes using(user_id);

答案 1 :(得分:0)

这样的事情应该做:

CREATE TABLE likes (
    like_id            serial PRIMARY KEY,
    user_id int
);

CREATE TABLE question_likes (
    question_id int,
    primary key (user_id, question_id)
) INHERITS (likes);

CREATE TABLE answer_likes (
    answer_id int,
    primary key (user_id, answer_id)
) INHERITS (likes);

可以使用merging

完成UNION
SELECT like_id, user_id, question_id, null as answer_id FROM question_likes q
UNION 
SELECT like_id, user_id, null as question_id, answer_id FROM answer_likes a;

您想要达到什么目标?