简体   繁体   中英

Select Two Values Based Off Same Column

I am trying to select two usernames in one row of a query one would be called 'username' and the second one say 'username2'. This is the code I have atm. The users table uses a primary key of 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

you need to join the table user twice

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

Here is the code for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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