Hi,
I'm trying to join three tables using a left join and a normal join. I know it is possible to achieve that using php by executing several queries, but I don't want this process be that expensive, so I'm trying to do the whole thing in one query.
Here is the useful information about my database schema:
table 1: matchResult
columns: match_id,team1,team2,status
table 2: teams
columns: team_id,team_name
table 3: predicts
columns: match_id,user_id
What I need is to return a list of matches whose status equals to two and join records from predicts table based on match_id and those whose user_id either equals to 2 or is null.
To achieve that I use the following query:
Code:
select matchResult.match_id,matchResult.team1,matchResult.team2,predicts.user_id from
matchResult LEFT join predicts using (match_id)
where matchResult.status=2 and (predicts.user_id=2 || predicts.user_id IS NULL);
This query returns the following information:
PHP Code:
+----------+-------+-------+---------+
| match_id | team1 | team2 | user_id |
+----------+-------+-------+---------+
| 5 | 92 | 94 | 2 |
| 7 | 104 | 98 | NULL |
| 8 | 105 | 107 | NULL |
| 9 | 109 | 96 | NULL |
| 10 | 111 | 103 | NULL |
| 11 | 95 | 97 | NULL |
| 12 | 101 | 110 | NULL |
| 13 | 93 | 108 | NULL |
+----------+-------+-------+---------+
8 rows in set (0.00 sec)
So far everything looks good, but I need to output the team names with their along side team IDs.
As you can see, the teams table contains a list of teams and their corresponding IDs. matchResult table has tow foreign keys (team1 and team2) who refer to the team_id of teams table.
I would like to know how I can join teams table to the existing query so that the output looks something like this:
PHP Code:
+----------+-------+-------+---------+-----------+-----------+
| match_id | team1 | team2 | user_id | team1 | team2 |
+----------+-------+-------+---------+-----------+-----------+
| 5 | 92 | 94 | 2 | Man U | Chelsea |
| 7 | 104 | 98 | NULL | Arsenal | Liverpool|
| 8 | 105 | 107 | NULL |
| 9 | 109 | 96 | NULL | and so on
| 10 | 111 | 103 | NULL |
| 11 | 95 | 97 | NULL |
| 12 | 101 | 110 | NULL |
| 13 | 93 | 108 | NULL |
+----------+-------+-------+---------+
8 rows in set (0.00 sec)
I have never had experience of executing such complex queries, so I would be glad if you help me with that.
Thanks