有没有一种方法可以从两个表中创建一个视图,这两个表中有一列是不同的?我现在遇到的问题是mysql告诉我有一个undefined index
-这非常有意义,因为在一半情况下,这个列不存在。
表格布局:
(post_rank_activity) ID, post_id, ... date (reply_rank_activity) ID, rank_id, ... date
What I want the resulting view to look like:
ID | Post_id | Reply_id | Date x x NULL x x NULL x x
And the 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)";
我得到的结果不是返回空值,而是返回“
reply_id
”字段的“post_id
”值,然后将所有其他值移到上面-请参见下文:ID邮寄ID回复ID日期
X X日期值X
X回复VAL日期VAL X
有什么想法吗?
最佳答案
联合必须在所有部分中以相同的顺序包含相同的列。您应该在联合的每个部分显式地选择/声明空列:
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