简体   繁体   English

SQL左连接外键两个表

[英]SQL Left Join Foreign Key Both Tables

I have a query in which I am joining a table of answers to their questions. 我有一个查询,我正在加入他们问题答案的表格。 Both tables have a foreign key that links back to a user table to determine who asked and who answered the question. 两个表都有一个外键,该外键链接回用户表以确定谁询问了谁以及谁回答了问题。

My question is, how can I modify the following query to make product_question . 我的问题是,如何修改以下查询以生成product_question userID AND product_answer . userIDproduct_answer userID show the name of the user from the User table instead of just the ID? userID显示User表中的用户名,而不仅仅是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

You can use two joins to the same table and aliases to distinguish them: 您可以对同一个表和别名使用两个连接来区分它们:

      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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM