UNION SELECT tables with inner join and GET values with "ALIAS"

时间:2015-10-30 22:43:28

标签: php mysql database

So I have 2 tables, Matches and Teams, what I want to do is get some values from the match and Inner join "Teams" to get the names of both teams and add them to a php array later on (getting it all in one sql)

Matches
- IDMatch
- IDLocalTeam
- IDVisitorTeam
- Time
- Half
- Stopped
Teams
- IDTeam
- name

What I have by now is

$query = "SELECT * FROM `Matches`
          INNER JOIN `Teams` ON `Matches`.IDLocalTeam = `Teams`.IDTeam 
          UNION SELECT * FROM `Matches` INNER JOIN `Teams` 
          ON `Matches`.IDVisitorTeam = `Teams`.IDTeam  
          ORDER BY IDMatch DESC;";

If someone could help me it would be great! Thanks alot

1 个答案:

答案 0 :(得分:0)

Wouldn't it be easier to use INNER JOIN twice? It's definitely quicker way of doing joins anyway.

SELECT 
    * 
FROM 
    `Matches` m
INNER JOIN `Teams` t1
    ON m.IDLocalTeam = t1.IDTeam
INNER JOIN `Teams` t2
    ON m.IDVisitorTeam = t2.IDTeam 
ORDER BY 
    m.IDMatch DESC;

Also start using aliases instead of table names to identify fields in query, it will SQL much smaller.