簡體   English   中英

mysql查詢從一個表中組合表

[英]mysql query combine table from one table

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

產生

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

PS表在word1上設置了1100萬行索引

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'

看到SqlFiddle

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM