内部连接查询 - 3个表

时间:2014-11-29 12:11:28

标签: mysql sql join

我正在尝试执行此查询以从三个表中打印数据。但不知何故,查询没有被执行。

SELECT l.locality_id, c.city_name, l.locality_name, cloud_site_location_outlet_localities.minimum_order, cloud_site_location_outlet_localities.delivery_time, cloud_site_location_outlet_localities.delivery_charge FROM `cloud_site_location_localities` l INNER JOIN `cloud_site_location_cities` c on l.city_id=c.city_id

执行上述查询时出现的错误是:

1054 - Unknown column 'cloud_site_location_outlet_localities.minimum_order' in 'field list'

但是,当我不得不仅显示两个表中的数据时,此查询工作正常。

SELECT l.locality_id, c.city_name, l.locality_name FROM `cloud_site_location_localities` l INNER JOIN `cloud_site_location_cities` c on l.city_id=c.city_id

我哪里错了?

当我使用以下查询将其导出为CSV时,我会获得冗余数据。在1000个条目中,我只得到400,然后重复400个。

这是我正在实施的代码

$sql = "SELECT l.locality_id, c.city_name, l.locality_name, o.minimum_order, o.delivery_time, o.delivery_charge FROM `cloud_site_location_localities` l INNER JOIN `cloud_site_location_cities` c ON l.city_id = c.city_id INNER JOIN `cloud_site_location_outlet_localities` o ON l.locality_id = o.locality_id";
$result = $DB->query($sql);


//$output = fopen($filename, 'c+');
$output = fopen('php://output', 'c+');
fputcsv($output, array('Location Id', 'City Name', 'Location Name','Minimum Order Amount','Delivery Time','Delivery Charge'));
$row = array();
$csv_output = "";
$csv_output .= "Locality Id,City Name,Locality Name,Minimum Order Amount,Delivery Time,Delivery Charge\n";
foreach($result as $locality_value)
{
    $row['locality_id'] =   $locality_value->locality_id;
    $row['city_name']       =       $locality_value->city_name;
    $row['locality_name']   =   $locality_value->locality_name;
    $row['minimum_order']   =   $locality_value->minimum_order;
    $row['delivery_time']   =   $locality_value->delivery_time;
    $row['delivery_charge'] =   $locality_value->delivery_charge;
    $csv_output .= trim($row['locality_id']).",".trim($row['city_name']).",".trim($row['locality_name']).",".trim($row['minimum_order']).",".trim($row['delivery_time']).",".trim($row['delivery_charge']).",,\n";
    fputcsv($output, $row);

}
fclose($output);
print $csv_output;

2 个答案:

答案 0 :(得分:1)

您缺少join的{​​{1}}条款。 E.g:

cloud_site_location_outlet_localities

答案 1 :(得分:0)

  

在mysql中连接三个表的简单结构

select *
from
    tbA a
        inner join
    tbB b
        on a.common = b.common
        inner join 
    tbC c
        on b.common = c.common