有没有办法从两个表创建一个视图,其中一个列在两个表中是不同的?我目前遇到的问题是MYSQL告诉我有一个undefined index
- 这是完全合理的,因为在一半的情况下,该列将不存在。
表格布局:
(post_rank_activity) ID, post_id, ... date (reply_rank_activity) ID, rank_id, ... date
我想要的结果视图如下:
ID | Post_id | Reply_id | Date x x NULL x x NULL x x
和SQL:
$rankView = "Create or replace view userRank as (
select PRA.id, PRA.post_id, PRA.user_id, PRA.vote_up, PRA.rank_date
From post_rank_activity PRA)
union All
(select RRA.id, RRA.reply_id, RRA.user_id, RRA.vote_up, RRA.rank_date
from reply_rank_activity RRA)";
我得到的结果,而不是返回null,它为“reply_id
”字段返回“post_id
”的值,然后将所有其他值移回 - 见下文:
ID | Post_id | Reply_id | Date x x date val x x reply val date val x
有什么想法吗?
答案 0 :(得分:5)
联合必须在所有部分中以相同的顺序包含相同的列。您应该在联合的每个部分中显式选择/声明空列:
SELECT PRA.id, PRA.post_id, NULL AS reply_id, PRA.user_id, PRA.vote_up, PRA.rank_date
FROM post_rank_activity PRA
UNION All
SELECT RRA.id, NULL AS post_id, RRA.reply_id, RRA.user_id, RRA.vote_up, RRA.rank_date
FROM reply_rank_activity RRA
答案 1 :(得分:3)
您的查询应该是
select PRA.id, PRA.post_id, null as Reply_id PRA.rank_date
From post_rank_activity PRA
union All
select RRA.id, null as post_id, RRA.reply_id, RRA.rank_date
from reply_rank_activity RRA