【问题标题】:mysql query combine table from one tablemysql查询从一张表中组合表
【发布时间】:2014-05-31 06:34:39
【问题描述】:

我的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

我需要在未找到 word2 的情况下获取 count=0。

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

附:该表有 1100 万行索引设置在 word1

附言提供的答案确实有效,但完成查询需要 20 秒。我需要自己以编程方式执行此操作以获得更好的性能。

【问题讨论】:

  • 所以你的意思是 word1_、word2_ 和 count_ 是不同的列??那么它们是什么?请更清楚地说明这些名称是什么??
  • 我已经编辑了我的问题

标签: mysql sql database optimization


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你真的不需要任何 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 条件

    【讨论】:

    • 这可行,但比 Raphaël Althaus 答案慢
    • 我在自己的系统上试过了。 Raphaël Althaus 的回答花了 20 秒(这对我来说太慢了)。您的回答花费了几分钟以上,所以我不得不放手并重新启动 mysql。不过还是谢谢你的努力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多