0

我有一个查询,我在其中加入了他们问题的答案表。两个表都有一个外键链接回用户表,以确定谁提出了问题,谁回答了这个问题。

我的问题是,如何修改以下查询以使product_question. userIDproduct_answeruserIDUser表中显示用户名而不仅仅是 ID?

                    SELECT `project_question`.`id` AS question_id, `project_question`.`question`, `project_question`.`userID` AS askedBy, 
                           `project_question`.`created` AS question_created, `project_answer`.`id` AS answer_id, 
                           `project_answer`.`answer`, `project_answer`.`userID` AS answeredBy, 
                           `project_answer`.`accepted`, `project_answer`.`created` AS answer_created
                      FROM `project_question`
                 LEFT JOIN `project_answer`
                        ON `project_question`.`id` = `project_answer`.`questionID`
                     WHERE `project_question`.`projectID` = $args[0]
                       AND `project_question`.`projectPhase` = 2
4

1 回答 1

2

您可以使用两个连接到同一个表和别名来区分它们:

      SELECT `project_question`.`id` AS question_id, 
             `project_question`.`question`, 
             q_user.`userName` AS askedBy, 
             `project_question`.`created` AS question_created, 
             `project_answer`.`id` AS answer_id, 
             `project_answer`.`answer`, 
             a_user.`userName` AS answeredBy, 
             `project_answer`.`accepted`, 
             `project_answer`.`created` AS answer_created
        FROM `project_question`
   LEFT JOIN `project_answer`
          ON `project_question`.`id` = `project_answer`.`questionID`
  INNER JOIN `User` AS q_user
          ON `project_question`.`userID` = q_user.`userID`
  INNER JOIN `User` AS a_user
          ON `project_answer`.`userID` = a_user.`userID`
       WHERE `project_question`.`projectID` = $args[0]
         AND `project_question`.`projectPhase` = 2
于 2013-11-14T15:33:36.603 回答