我有两张桌子,我想彼此结合。在这一点上,我正在使用UNION来组合它们,这非常适合我的所有需求,但有一点。由于UNION用T2代替T1中的所有内容,因此T3.votes将为0.但我不希望它为0 - 我希望它保持T1.votes的状态(不要介意T2只有四行长)因为我已经设法将这些结合在一起,但我只是没有得到T3.votes来显示T1.votes内容。)
我如何做到这一点?澄清:除T2.votes外,一切都应该合并。
T1
+-----------+-------+---------------+
| CANDIDATE | VOTES | RANKED_CHOICE |
+-----------+-------+---------------+
| 1 | 8 | 0 |
| 2 | 1 | 0 |
| 3 | 2 | 0 |
| 4 | 4 | 0 |
| 5 | 2 | 0 |
| 6 | 3 | 0 |
+-----------+-------+---------------+
T2
+-----------+-------+---------------+
| CANDIDATE | VOTES | RANKED_CHOICE |
+-----------+-------+---------------+
| 2 | 0 | 4 |
| 3 | 0 | 1 |
| 4 | 0 | 2 |
| 5 | 0 | 1 |
+-----------+-------+---------------+
COMBINED TABLE AS I EXPECT IT TO BE (T3)
+-----------+-------+---------------+
| CANDIDATE | VOTES | RANKED_CHOICE |
+-----------+-------+---------------+
| 1 | 8 | 0 |
| 2 | 1 | 4 |
| 3 | 2 | 1 |
| 4 | 4 | 2 |
| 5 | 2 | 1 |
| 6 | 3 | 0 |
+-----------+-------+---------------+
答案 0 :(得分:0)
如果T1的所有候选人都在T2,你可以进行左连接。
select t1.candidate, max(t1.votes,ifnull(t2.votes,0)), max(t1.ranked_choice,ifnull(t2.ranked_choice,0))
from t1 left join t2
on t1.candidate = t2.candidate;
否则,您可以将T1和T2的并集作为子查询,并从此子查询中获取总票数或最大值。
select candidate, sum(votes),max(ranked_choice) from
(
select candidate,votes,ranked choice from t1
union
select candidate,votes,ranked choice from t2
) sub
group by candidate;
编辑:我的查询中有两个小错误 - 使用最大()而不是max()和#34;排名选项之间的下划线":
select t1.candidate, greatest(t1.votes,ifnull(t2.votes,0)) as votes, greatest(t1.ranked_choice,ifnull(t2.ranked_choice,0)) as rank
from t1 left join t2
on t1.candidate = t2.candidate;
select candidate, sum(votes),max(ranked_choice) from
(
select candidate,votes,ranked_choice from t1
union
select candidate,votes,ranked_choice from t2
) sub
group by candidate;
两个查询都会产生所需的结果。