2010-08-30 48 views
2

所以我有一個基本的問題,如何從外部聯接語句的表中獲取變量。從第一個表中獲取變量左加入

mysql_query("SELECT * 
       FROM (cal_events 
      left join cal_cities on cal_events.city_id = cal_cities.id) 
      left join cal_genre on cal_events.genre_id = cal_genre.id 
       WHERE start_day BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 DAY) 
            AND DATE_ADD(CURDATE(), INTERVAL 5 DAY) 
      order by start_day"); 

while($info = mysql_fetch_array($data)) { 
    echo $info['id']; 
} 

這將回聲出流派的ID,但我需要從cal_events的ID ...使用$信息[ 'cal_events.id']剛剛拋出錯誤

HELP!

回答

0
mysql_query("SELECT * , cal_events.id as cal_id 
         FROM (cal_events 
        left join cal_cities on cal_events.city_id = cal_cities.id) 
        left join cal_genre on cal_events.genre_id = cal_genre.id 
         WHERE start_day BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 DAY) 
              AND DATE_ADD(CURDATE(), INTERVAL 5 DAY) 
        order by start_day"); 
    while($info = mysql_fetch_array($data)) { 
     echo $info['cal_id']; 
    } 
+0

工作就像一個魅力!謝謝 – Aaron 2010-08-30 05:27:19

1

幾乎所有的mysql接口都可以在你進行連接的時候使用,並且這些表具有相同的列名,只有該名的最後一次出現在數組中。爲了以防萬一獲取此別名的列:

SELECT cal_events.id as cal_events_id, cal_cities.* FROM (cal_events left join cal_cities on cal_events.city_id = cal_cities.id) left join cal_genre on cal_events.genre_id = cal_genre.id WHERE start_day BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 DAY) AND DATE_ADD(CURDATE(), INTERVAL 5 DAY) order by start_day 

顯然是不會得到調用中的所有列,我只是他們中省略,因爲我不知道他們是什麼。你應該單獨表達它們,並別名任何需要別名的別名。

相關問題