This is my first post, but I’ve been reading here for ages taking in a lot of great information.
Please bear with me as I try to explain my predicament. I wasn’t even sure how to label my question, since I don’t really know the terminology for what I’m trying to do. I’m a beginner of PHP/MySQL (this will become painfully obvious when you see my question), but I’m eager to learn.
Anyway, here goes:
I have two tables, named Games and Teams.
mysql> describe games;
+-----------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| homeTeam | int(11) | NO | | NULL | |
| awayTeam | int(11) | NO | | NULL | |
| homeScore | int(11) | NO | | NULL | |
| awayScore | int(11) | NO | | NULL | |
| homeOdds | decimal(10,2) | NO | | NULL | |
| drawOdds | decimal(10,2) | NO | | NULL | |
| awayOdds | decimal(10,2) | NO | | NULL | |
| gameDate | date | NO | | NULL | |
+-----------+---------------+------+-----+---------+----------------+
and
mysql> describe teams;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| team | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
I would like the fields Games.homeTeam and Games.awayTeam to do a lookup for their values in the Teams.id and Teams.team fields. Basically Games.homeTeam should find its equivalent in Teams.id. Simple enough. However, I would like both Games.homeTeam and Games.awayTeam to look in the Teams table within the same SQL statement.
I figured maybe something like this would work:
$result = mysql_query("SELECT * FROM Games g, Teams ht, Teams at where g.homeTeam = ht.id AND g.awayTeam = at.id ORDER BY g.gameDate") or die(mysql_error());
and then to pick the rows up:
while($row = mysql_fetch_array($result)) { echo "Home Team: " . $row['ht.team'];}
That’s a no go, as I get a mysql error saying there’s no index named ht.team.
I hope it’s fairly clear what I’m trying to achieve here. How should I go about this? I assume I have to use aliases of some sort, but I can’t wrap my head around as to what the SQL statement should look like to accomplish what I want.
Don’t use
SELECT *with join queries! Always be explicit about the columns you need in yourSELECTlist, and supply column aliases:In your PHP, access them via their aliases, for example:
By the way, although your method of implicit (comma-separated tables and conditions in the
WHEREclause) joins will work, using explicit joining is often recommended. It is a newer syntax, and will allow easier expansion intoLEFT JOINorRIGHT JOINwhen the need arises: