MySQL通过不同的“列名”间接选择值

时间:2012-11-21 17:54:41

标签: mysql

  

可能重复:
  MySQL use column names from another table

我有两张桌子:

  • TABLE_1,其中包含从任何文本中提取的一些单词;以及

  • TABLE_2,相关文字中的单词(以列为单位)

enter image description here

我想生成一个TABLE_3,其中包含Author_Id和文本中的单词(行):

Table 3 http://www.infociencias.net/images/tab3.jpg

如何在MySQL中执行此操作?

1 个答案:

答案 0 :(得分:0)

这是您尝试执行的UNPIVOT,但MySQL没有UNPIVOT功能,因此您需要使用UNION ALL复制它:

SELECT c.author_id, words, value
FROM Table1 A
INNER JOIN
(
  select author_id, alfa value, 'alfa' col
  from table2
  union all
  select author_id, car value, 'car' col
  from table2
  union all
  select author_id, zoom value, 'zoom' col
  from table2
) C 
  ON A.words = C.col
order by c.author_id

请参阅SQL Fiddle with Demo

结果:

| AUTHOR_ID | WORDS | VALUE |
-----------------------------
|       123 |  alfa |     3 |
|       123 |  zoom |     0 |
|       123 |   car |     0 |
|       157 |  alfa |     0 |
|       157 |  zoom |     2 |
|       157 |   car |     0 |
|       332 |  alfa |     1 |
|       332 |  zoom |     0 |
|       332 |   car |     3 |
|       519 |   car |     0 |
|       519 |  alfa |     0 |
|       519 |  zoom |     0 |
|       588 |   car |     1 |
|       588 |  alfa |     5 |
|       588 |  zoom |     0 |
|       777 |   car |     0 |
|       777 |  alfa |     0 |
|       777 |  zoom |     1 |
|       804 |   car |     7 |
|       804 |  alfa |     0 |
|       804 |  zoom |     5 |
相关问题