简体   繁体   中英

Inner join multiple times on same table on same column

I have two mySQL tables:

1: id, agent, promoter, promoterrank, prevrank, newrank, promotiontime

2: id, rank

newrank and promoter ranks are INTS that correspond to the ID in table 2 (ex: Trainee = 2, Supervisor = 4, etc...)

I'm trying to INNER JOIN A to B in a way that I can show the actual name of the rank as opposed to the ID related to the rank. I've successfully done this for newrank, but no matter what I try to do for promoterrank it just does not work. I appreciate all the help.

This is the SQL query im using:

SELECT A.*,B.rank as brank,DATE_FORMAT(promotiontime, '%Y-%m-%dT%H:%i:%s0Z') FROM promotions A 
INNER JOIN ranks B ON A.newrank = B.id 
WHERE agent='".$_POST['agent']."' ORDER BY id DESC

And my PHP:

<td><?php echo $row['brank']; ?></td>
<td><a href="profile.php?user=<?php echo $row['promoter']; ?>"><?php echo $row['promoter']; ?></a></td>
<td><?php echo $row['promoterrank']; ?></td>

You want decode two value for rank (one for newrank and one for promoterrank ) then you should join tha table rank two time eg:

    SELECT A.*
      , B.rank as newrank
      , C.rank as promoterrank
      DATE_FORMAT(promotiontime, '%Y-%m-%dT%H:%i:%s0Z') 
    FROM promotions A 
    INNER JOIN ranks B ON A.newrank = B.id 
    INNER JOIN ranks C ON A.promoterrank = C.id
    WHERE agent='".$_POST['agent']."' ORDER BY id DESC

anyway you should avoid the use of php var in sql code.. (you are at risk for sqlinjection) so take a look at prepared statement and binding param

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