SQL(JOIN) - 从一列到两列

时间:2016-11-24 09:48:53

标签: mysql sql join

SELECT a.cp_node_id,
       a.cmi_node_id,
       a.user_id,
       a.learner_name,
       a.completion_status,
       a.success_status,
       b.id title,
       c.dep,
       d.field_id,
       d.value
       FROM cmi_node a
JOIN cmi_objective b
  ON a.cmi_node_id=b.cmi_node_id
 AND a.completion_status = 'completed'
 AND a.success_status = 'passed'
 AND a.cp_node_id = '1'
JOIN usr_data c
  ON a.user_id = c.usr_id
JOIN udf_text d
  ON a.user_id = d.usr_id
GROUP BY a.cmi_node_id

在我的" D"表我有一列,有两个结果,例如:

ID: field_id:  value:
1   1          test
1   2          text2
2   1          test
2   2          text3
3   1          test2
3   2          text6
etc...

在field_in中始终为1或2。

我需要打印来自" cmi_node"的所有用户,例如:

user_id  learner_name
1        George
2        Michel
3        James

我想在" D"中添加两列。表: 例如:

user_id  learner_name  field_in_first field_in_second value_first value_second
1        George        1              2               test        text2
2        Michel        1              2               test        text3
3        James         1              2               test2       text6

谢谢

1 个答案:

答案 0 :(得分:1)

两次加入同一张桌子。

JOIN udf_text d1 ON a.user_id = d.usr_id AND field_id = 1
JOIN udf_text d2 ON a.user_id = d.usr_id AND field_id = 2

然后你可以访问d1.field_id,d2.field_id,d1.value和d2.value