val*_*nko 3 mysql sql database optimization
我的mysql表看起来像这样:
word1 word2 count
a c 1
a d 2
a e 3
a f 4
b c 5
b d 6
b g 7
b h 8
Run Code Online (Sandbox Code Playgroud)
"a"和"b"是用户输入 - 从表中选择*,其中word1 ='a'或word1 ='b' - 得到~10000行
我需要一个查询来获取:word1是intput"a"的列
word1_是输入"b"的列
word2和word2_是同一列,因此可以忽略其中一个
我需要结合上表中的表格.例如这个查询:
select
t1.word1, t1.word2, t1.count,
t2.word1 as word1_, t2.word2 as word2_, t2.count as count_
from table t1
join table t2 on t1.word2 = t2.word2
where t1.word1 = 'a' and t2.word1 = 'b'
Run Code Online (Sandbox Code Playgroud)
产生
word1 word2 count word1_ word2_ count_
a c 1 b c 5
a d 2 b d 6
Run Code Online (Sandbox Code Playgroud)
我需要得到count = 0,其中找不到word2.
word1 word2 count word1_ word2_ count_
a c 1 b c 5
a d 2 b d 6
a e 3 b e 0
a f 4 b f 0
a g 0 b g 7
a h 0 b h 8
Run Code Online (Sandbox Code Playgroud)
PS表中有11万行索引设置 word1
PPS提供的答案确实有效,但完成查询需要20秒.我需要自己以编程方式执行此操作以获得更好的性能.
你需要一个FULL OUTER JOIN ...在mysql中不存在.
你可以这样做.
select
t1.word1, t1.word2, t1.count,
coalesce(t2.word1, 'b') as word1_, t1.word2 as word2_, coalesce(t2.count, 0) as count_
from table1 t1
left join table1 t2 on t1.word2 = t2.word2 and t2.word1 = 'b'
where t1.word1 = 'a'
union
select
coalesce(t2.word1, 'a'), t1.word2 , coalesce(t2.count, 0),
t1.word1 as word1_, t1.word2 as word2_, t1.count
from table1 t1
left join table1 t2 on t1.word2 = t2.word2 and t2.word1='a'
where t1.word1 = 'b'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |