tags:

views:

35

answers:

2

Hello guys. I have had a good think and just can't get my head around this.

I have a table (transfers) like the following

id | playerid | old | new | amount

They are all integers.

I am joining this table (teams) to the following

id | name | founded

The join is going to be on old and new.

old and new are both ints and i need the name from the team table. Is it possible to find out both of these names in one query?

Thanks

+2  A: 

Yes it is:

SELECT t.id, 
       t.playerid, 
       t_old.name old_team, 
       t_new.name new_team, 
       t.amount
FROM   transfers t
JOIN   teams t_old ON (t_old.id = t.old)
JOIN   teams t_new ON (t_new.id = t.new);

Note that JOIN is a synonym for INNER JOIN.

Test case:

CREATE TABLE transfers (id int, playerid int, old int, new int, amount int);
CREATE TABLE teams (id int, name varchar(100), founded datetime);

INSERT INTO teams VALUES (1, 'Man Utd', '1900-01-01');
INSERT INTO teams VALUES (2, 'Liverpool', '1890-01-01');

INSERT INTO transfers VALUES (1, 1, 1, 2, 99999999);

Result:

+------+----------+----------+-----------+----------+
| id   | playerid | old_team | new_team  | amount   |
+------+----------+----------+-----------+----------+
|    1 |        1 | Man Utd  | Liverpool | 99999999 |
+------+----------+----------+-----------+----------+
1 row in set (0.00 sec)
Daniel Vassallo
Thanks a lot, I will implement this and hopefully give it the green tick :)
Luke
Just read the extra you added. That is perfect. I am just trying to improve and know I should store the teams as ID in one database and refer to it elsewhere.
Luke
@Luke: Your tables look properly defined :)
Daniel Vassallo
@Luke: The key is that you *have* to use table aliases when using two or more of the same table in a query.
OMG Ponies
Thankyou, really helpful!
Luke
A: 

Note that if you ever have a record where new matches an entery and old doesn't (or vice versa) the inner join will fail to match. Use outer joins then. but in the case of a transfer, that doesn't make sense. :) Make sure new and old are NOT NULL.

DGM