3

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?

4

2 に答える 2

5

ユニオンには、すべてのパーツで同じ順序で同じ列が含まれている必要があります。ユニオンの各部分でnull列を明示的に選択/宣言する必要があります。

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
于 2012-11-09T17:48:23.000 に答える
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
于 2012-11-09T17:48:52.067 に答える