简体   繁体   中英

SQL multiple JOIN to the same column

I have 3 tables

outcome table

outcome_id, outcome

refs table

refs_id, branchno, colleagueid, colleague2id, datestamp

colleague Table

colleague_id, name, branch

Here is the mysqli statement that I am using to draw the colleague name rather than the number. This also works for the outcome instead of outcome_id.

The issue i'm having is I cannot join colleague2id to a name from the colleague table.

SELECT * FROM refs
JOIN colleague ON colleague.colleague_id=refs.colleagueid
JOIN outcome ON outcome.outcome_id=refs.outcome
WHERE branchno ='{$_SESSION["branchinfo"]["storeno"]}'

Output into PHP

echo "<td>".$row["refs_id"])."</td>" . "
    <td>".$row['name'] . "</td>
    <td>".$row['colleague2id'] . "</td>
    <td>".$row['outcome'] . "</td>      

How can I get $row['colleague2id'] to show colleague.name instead of the id number?

Sorry if this isn't formatted correctly its my first post.

You need two join for colleague table (using alias a and b )

  SELECT * 
  FROM refs
  JOIN colleague  as a ON a.colleague_id=refs.colleagueid
  JOIN colleague  as b ON b.colleague_id=refs.colleague2id
  JOIN outcome ON outcome.outcome_id=refs.outcome
  WHERE branchno ='{$_SESSION["branchinfo"]["storeno"]}'

but for a clear select you should set explictally the columns name

Since there are two colleagueid s in refs table, you'd need to JOIN the colleague table twice to be able to get names for both those columns.

The query should be:

SELECT refs_id, branchno, colleagueid, colleague2id, datestamp,
       c1.name AS colleague1name, c2.name AS colleague2name,
       outcome_id, o.outcome
    FROM refs
         JOIN colleague c1 ON c1.colleague_id = refs.colleagueid
         JOIN colleague c2 ON c2.colleague_id = refs.colleague2id
         JOIN outcome   o  ON o.outcome_id    = refs.outcome
    WHERE branchno ='{$_SESSION["branchinfo"]["storeno"]}'

Then, PHP can access the names as:

$row['colleague1name']
$row['colleague2name']

The only other thing which should be considered is that the query above is prone to SQL Injection attacks and hence prepared statements using MySQLi or PDO should be implemented instead.

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