使用两列将两个SQL表相互连接起来

时间:2012-06-10 11:08:30

标签: php mysql sql join

问题:

我正在尝试将分级表(betyg_essays)中两列中的id“转换”为另一个表(betyg_users)中这些用户的真实姓名。

评分表(betyg_essays)如下所示:

enter image description here

用户表(betyg_users)如下所示:

enter image description here

PHP代码(目前为止):

$query = 'SELECT * FROM betyg_essays JOIN betyg_users ON betyg_essays.Examiner = betyg_users.UID';

Examiner / Supervisor列(betyg_essays)对应于UID列(betyg_users)。

所需的输出应该是(使用名字/姓氏列):

  1. 考官:约翰霍普金斯。主管:Mike Baker。
  2. 考官:约翰霍普金斯。主管:Mike Baker。
  3. 非工作SQL查询:

    $query = "SELECT 
                (u1.Firstname + ' ' + u1.Lastname) AS Examiner, 
                (u2.Firstname + ' ' + u2.Lastname) AS Supervisor
            FROM betyg_essays grade
                INNER JOIN betyg_users u1 ON grade.Examiner = u1.UID
                INNER JOIN betyg_users u2 ON grade.Supervisor = u2.UID";
    

4 个答案:

答案 0 :(得分:2)

SELECT
CONCAT(u1.FirstName, ' ', u1.LastName) AS Examiner,
CONCAT(u2.FirstName, ' ', u2.LastName) AS Supervisor
FROM betyg_essays e
INNER JOIN betyg_users u1 ON e.Examiner = u1.UID
INNER JOIN betyg_users u2 ON e.Supervisor = u2.UID

我没有尝试过代码,您可能需要进行一些调整。

更新:修正了ID

INNER JOIN betyg_users u2 ON e.Supervisor = u2.UID

UPDATE2:

我已将+更改为CONCAT功能。显然,MySQL处理字符串的方式与SQL Server不同。

答案 1 :(得分:2)

在这里,你需要先加入user_table两次才能获得考官用户名,第二次加入supervisor用户名

SELECT (g1.FirstName + ' ' + g1.LastName) AS Examiner,' , (g2.FirstName + ' ' + g2.LastName) AS Supervisor
FROM grading_table grade
INNER JOIN user_table g1 ON grade.examiner = g1.uid
INNER JOIN user_table g2 ON grade.supervisor = g2.uid

答案 2 :(得分:2)

最终解决方案:

$query = "SELECT 
            CONCAT (u1.Firstname, ' ', u1.Lastname) AS Examiner, 
            CONCAT (u2.Firstname, ' ', u2.Lastname) AS Supervisor
        FROM betyg_essays grade
            INNER JOIN betyg_users u1 ON grade.Examiner = u1.UID
            INNER JOIN betyg_users u2 ON grade.Supervisor = u2.UID";

答案 3 :(得分:1)

试试这个

SELECT CONCAT(betyg_users.`Firstname`," ",betyg_users.`Lastname`) AS `examiner_name`,
CONCAT(betyg_users.`Firstname`," ",betyg_users.`Lastname`) AS `superviser_name`
FROM `betyg_essays`
INNER JOIN `betyg_users` ON betyg_essays.`Examiner` = betyg_users.`UID` 
INNER JOIN `betyg_users` ON betyg_essays.`Supervisor` = betyg_users.`UID`;