user725913
user725913

Reputation:

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?

Upvotes: 3

Views: 2685

Answers (2)

rs.
rs.

Reputation: 27417

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

Upvotes: 3

lc.
lc.

Reputation: 116438

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

Upvotes: 5

Related Questions