gpt4 book ai didi

mysql - SQL 左连接外键两个表

转载 作者:行者123 更新时间:2023-11-29 08:18:56 24 4
gpt4 key购买 nike

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

我的问题是,如何修改以下查询以使 product_question.userID AND product_answer.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

最佳答案

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

      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

关于mysql - SQL 左连接外键两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com