使用Left Outer Join - PDO从多个表中获取数据

时间:2014-10-13 08:37:01

标签: php mysql pdo inner-join outer-join

我正在尝试使用LEFT OUTER JOIN连接到3个表。我不确定我是否正确这样做。

表格是:费率,国家/地区和服务类型

查询:

$sql = "SELECT rates.rate_id, rates.initial_change, service_types.service, countries.country 
FROM rates 
LEFT OUTER JOIN service_types ON rates.service_id = service_types.serviceType_id 
LEFT OUTER JOIN countries ON rates.from_id = country.country_id 
LEFT OUTER JOIN countries ON rates.to_id = country.country_id 
ORDER BY service_types.serviceType_id ASC";
$statement = $con_db->exec($sql);
$result = $statement->fetchAll();//error points to this line

这是错误消息:

致命错误:在

中的非对象上调用成员函数fetchAll()

1 个答案:

答案 0 :(得分:1)

我注意到的一件事是您访问表格的方式不正确。我猜测SQL无效,从exec返回null。尝试将您的查询更改为:

$sql = "SELECT rates.rate_id, rates.initial_change, service_types.service, countries1.country, countries2.country 
FROM rates 
LEFT OUTER JOIN service_types ON rates.service_id = service_types.serviceType_id 
LEFT OUTER JOIN countries as countries1 ON rates.from_id = countries1.country_id 
LEFT OUTER JOIN countries as countries2 ON rates.to_id = countries2.country_id 
ORDER BY service_types.serviceType_id ASC";

注意国家/地区已更改为countries1&在连接条件中的countries2,以及select中的列。