我们有两个带有英语单词的表: words_1和words_2,它们都有字段( word作为VARCHAR,ref作为INT),其中word -它是一个英文单词,ref -引用在另一个(第三)表上(它并不重要)。
在每个表中,所有单词都是唯一的。第一个表包含一些不在第二个表中的单词(相反,第二个表包含一些独特的单词)。
但是两张桌子上的大多数单词是一样的。
需要获取:包含所有不同单词和引用的结果表。
初始条件
示例
words_1
________
Health-1
Car-3
Speed-5
words_2
_________
Health-2
Buty-6
Fast-8
Speed-9
Result table
_____________
Health-1
Car-3
Speed-5
Buty-6
Fast-8发布于 2014-10-27 13:48:11
select word,min(ref)
from (
select word,ref
from words_1
union all
select word,ref
from words_2
) t
group by word发布于 2014-10-27 13:45:10
尝试使用full outer join
select coalesce(w1.word, w2.word) as word, coalesce(w1.ref, w2.ref) as ref
from words_1 w1 full outer join
words_2 w2
on w1.word = w2.word;唯一不起作用的情况是,如果ref可以在两个表中都是NULL。在这种情况下,将on更改为:
on w1.word = w2.word and w1.ref is not null and w2.ref is not null如果您想提高性能,只需在表上创建一个索引:
create index idx_words1_word_ref on words_1(word, ref);
create index idx_words2_word_ref on words_2(word, ref);一个join是非常可行的,即使没有索引,Server也应该足够聪明,能够找到一个合理的实现。
https://stackoverflow.com/questions/26588924
复制相似问题