2012-05-23 170 views
18

有誰知道我怎麼可以做一個內部聯接和別名值,以便他們不會相互覆蓋?MySQL INNER JOIN別名

SELECT home, away, g.network, g.date_start 
    FROM game g 
    INNER JOIN team t ON (
     (t.importid = g.home) as home 
     OR 
     (t.importid = g.away) as away 
    ) 
    ORDER BY date_start DESC 
    LIMIT 7 

解決(以下後,在這裏幫助是我的最終查詢)

SELECT 
     home.market AS home_market, 
     away.market AS away_market, 
     g.network, 
     g.date_start 

    FROM game AS g 
    INNER JOIN team AS home ON (
     home.importid = g.home 
    ) 
    INNER JOIN team AS away ON (
     away.importid = g.away 
    ) 

    ORDER BY g.date_start DESC 
    LIMIT 7 

回答

28

你需要參加兩次:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g 
INNER JOIN team AS home 
    ON home.importid = g.home 
INNER JOIN team AS away 
    ON away.importid = g.away 
ORDER BY g.date_start DESC 
LIMIT 7 
1

使用一個單獨的列,以指示連接條件

:如果你看到我的代碼它看起來更清晰
SELECT t.importid, 
     case 
      when t.importid = g.home 
      then 'home' 
      else 'away' 
     end as join_condition, 
     g.network, 
     g.date_start 
FROM game g 
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away) 
ORDER BY date_start DESC 
LIMIT 7 
+0

嘿,這很酷 - 但我試圖把'家'和'走'在同一行。我知道我的問題沒有太多意義。 :)如果我想要一個單獨的主/行記錄,這確實有效。 – JREAM