有没有办法从两个表创建视图,其中一个列在两个表中是不同的?我目前遇到的问题是MYSQL告诉我有一个未定义的索引 – 这是完全合理的,因为在一半的情况下,该列将不存在.
表格布局:
(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,它返回“post_id”字段的“reply_id”值,然后将所有其他值转移 – 见下文:
ID | Post_id | Reply_id | Date
x x date val x
x reply val date 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
标签:mysql,view
来源: https://codeday.me/bug/20190725/1536767.html