选择两个基于相同列的值

时间:2013-01-21 08:17:43

标签: mysql sql select pdo

我试图在查询的一行中选择两个用户名,一个称为“用户名”,第二个称为“username2”。这是我的代码。 users表使用user_id的主键。

SELECT
  r.report_id,
  r.poster_id,
  r.reporter_id,
  u.username,
  (2nd username)
FROM reports r,
  users u
WHERE r.report_id = :report_id
    AND r.reporter_id = u.user_id
    AND r.poster_id = u.user_id

2 个答案:

答案 0 :(得分:2)

您需要加入表格user两次

SELECT 
        r.report_id,
        r.poster_id,
        r.reporter_id,
        u.username AS ReporterName,
        b.userName as PosterName
FROM
        reports r
        INNER JOIN users u      
            ON r.reporter_id=u.user_id
        INNER JOIN users b
            ON r.poster_id=b.user_id
WHERE
        r.report_id=:report_id

答案 1 :(得分:1)

这是MySQL的代码

        SELECT
          r.report_id,
          r.poster_id,
          r.reporter_id,
          u.username,
          u.username username2,
        FROM reports r,
          users u
        WHERE r.report_id = :report_id
            AND r.reporter_id = u.user_id
            AND r.poster_id = u.user_id