从Left Join中的第一个表获取变量

时间:2010-08-30 04:57:12

标签: php mysql

所以我有一个基本问题,即如何从外连接语句的表中获取变量。

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 ...使用$ info ['cal_events.id']只会抛出错误

HELP!

2 个答案:

答案 0 :(得分:1)

在你进行连接时,几乎所有的mysql接口都有,并且表只有相同的列名,只有该名称的最后一次出现在数组中。要获得arround这个别名你的列:

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

显然,我不会在调用中获取所有列,因为我不知道它们是什么。你应该单独表达它们,并将任何需要别名的别名。

答案 1 :(得分: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'];
    }