简体   繁体   中英

Create view from two tables with different column names

Is there a way to create a view from two tables, where one of the columns is different among the two tables? The problem I am currently running into is that MYSQL is telling me that there is an undefined index - which makes perfect sense since, in half of the cases, the column won't exist.

Table Layout:

(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)";

And the result I'm getting, instead of returning null, it's returning the value of " reply_id " for the " post_id " field and then shifting all of the other values over - see below:

ID | Post_id      | Reply_id     | Date
x       x             date val      x
x       reply val     date val      x

Any ideas?

Unions must contain the same columns in the same order across all parts. You should explicitly select/declare the null columns in each part of the union:

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

Your query should look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM