mysql查询从一个表中组合表

时间:2014-04-16 11:48:50

标签: 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

“a”和“b”是用户输入 - 从表中选择*,其中word1 ='a'或word1 ='b' - 得到~10000行

我需要一个查询来获取: word1是输入“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'

产生

word1   word2   count   word1_  word2_  count_  
a       c       1       b       c       5
a       d       2       b       d       6

我需要得到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

P.S。该表在word1

上设置了1100万行索引

P.P.S。提供的答案确实有效,但完成查询需要20秒。我需要自己编程以获得更好的性能。

2 个答案:

答案 0 :(得分:5)

你需要一个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'

请参阅SqlFiddle

答案 1 :(得分:1)

你真的不需要任何UNION或OUTER JOIN

SELECT 'a' word1
     , b.word2
     , max(CASE word1 WHEN 'a' THEN count ELSE 0 END) count
     , 'b' _word1
     , b.word2 _word2
     , max(CASE word1 WHEN 'b' THEN count ELSE 0 END) _count
FROM   words a
       INNER JOIN (SELECT DISTINCT word2
                   FROM   words
                   WHERE  word1 IN ('a', 'b')) b ON a.word2 = b.word2
GROUP BY b.word2
ORDER BY b.word2

演示:SQLFiddle
在演示中,我添加了一行,其中word1既不是' a'或者' b',如果你想要word2的每个值而不管word1的值只是去掉子查询的WHERE条件