sql left join无法正常工作

时间:2016-02-25 09:03:09

标签: php mysql left-join

我希望从inv_site_item 'item_id' in inv_sie_item = 'item_code'中的inv_items表中获取总转移项目,我也从包装表中获取包装,该表仅在此查询中正常工作inv_site_item提出问题。

错误是:Unknown column 'inv_site_item.site_id' in 'field list'

$where .= " AND inv_items.item_code = $item_code";

$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
    . " COUNT(inv_site_item.site_id) `transfer_out`, COUNT(inv_site_item.location_site_id) `transfer_in`  FROM inv_items"
            . " left join "
            . "inv_packing as packing on packing.id=inv_items.packing"
            . " left join "
            . "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
    . " WHERE item_code !='' " . $where . ""; 

3 个答案:

答案 0 :(得分:0)

您必须使用表格别名transfer,所以:

改变
inv_site_item.site_id

transfer.site_id

同时inv_site_item.location_site_idtransfer.location_site_id

答案 1 :(得分:0)

对于任何与查询相关的错误,如果可能,应始终检查以打印查询。您的“WHERE”子句未正确填充。

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的'WHERE item_code!='''附近使用正确的语法

这意味着您的查询在“WHERE”子句附近出错。

打印您的$ query变量以查看构建的实际查询,然后您将能够找到错误并进行修复。

<?php echo "<pre>"; print_r($query); echo "</pre>"; ?>

答案 2 :(得分:0)

您必须使用表格别名transfer,所以:

改变
inv_site_item.site_id

transfer.site_id

同时inv_site_item.location_site_idtransfer.location_site_id

并将$where .= " AND inv_items.item_code = $item_code";更改为

$where .= "inv_items.item_code = $item_code";

将查询语句更改为

$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
    . " COUNT(transfer.site_id) `transfer_out`, COUNT(transfer.location_site_id) `transfer_in`  FROM inv_items"
            . " left join "
            . "inv_packing as packing on packing.id=inv_items.packing"
            . " left join "
            . "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
    . " WHERE " . $where . " AND item_code !=' '"; 

为了让不为空条款终于来了......