【问题标题】:select columns from 2 tables with rows as column having same id从 2 个表中选择列,其中行作为具有相同 id 的列
【发布时间】:2017-01-06 06:20:03
【问题描述】:

我有 2 个包含不同列的表,并且两者的 tokenid 相同。 第二个表有多行具有相同的tokenid,其他列不同。

现在,我需要从两个表中选择令牌 ID 相同的列,在第二个表中,必须将具有相同令牌 ID 的行转换为列。

表 1:

tokenid   acolumn1   acolumn2   acolumn4
   1       fname1     mname1     lname1
   2       fname2     mname2     lname2

表 2:

id   tokenid   bquestion   banswer
 1       1     questiona   answera
 2       1     questionb   answerb
 3       2     questiona   answera
 4       2     questionb   answerb
 5       3     questionc   answerc

结果应该是

tokenid   acolumn1   acolumn2   acolumn3   bquestion1   banswer1   bquestion2   banswer2   bquestion3   banswer3
  1        fname1     mname1     lname1     questiona   answera    questionb    answerb    null           null  
  2        fname2     mname2     lname2     questiona   answera    questionb    answerb    questionc    answerc

我尝试先用 distinct 查询第二个表,并将其用作子查询来加入 table1。但是数据库在表 2 中有超过 200,000 行,并且与通过 acolumn1 选择的 tokenid 匹配将产生大约 20000 行结果。所以我的查询没有完成。有没有优化的方法来解决这个问题?

P.S:我想补充一点,我使用 pdo 使用 php 进行查询

【问题讨论】:

  • MySQL pivot table的可能重复
  • 到目前为止你尝试过什么?
  • @shA.t 就像我说的那样,尝试使用 LEFT JOIN,使用子查询,例如 Select colums from (select columns from .... )。问题是,我有巨大的数据库,大多数查询都无法成功加载

标签: mysql sql


【解决方案1】:

试试这个代码,它将你的 table1 和 table2 的所有列连接起来。

SELECT table1.tokenid, table1.acol1, table1.acol2, table1.acol3, table2.bquestion, table2.banswer FROM table1
    INNER JOIN table2
    ON table1.tokenid=table2.tokenid

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多