使用左连接连接多个表

时间:2012-09-05 11:28:14

标签: php mysql join

我有以下查询:

$products_query = 
  tep_db_query("select op.orders_products_id, op.orders_id, op.products_id, ".
                      "op.products_model, op.products_name, op.products_quantity, ".
                      "p.products_id from " . TABLE_ORDERS_PRODUCTS . " op " .
                  " left join " . TABLE_PRODUCTS . " p " .
                  " on (op.products_id = p.products_id) where orders_id = '" . 
                  (int)$cuttinglist['orders_id'] . "'");

这将两个表连接在一起,具有相同的id。我如何加入名为的第3个表:

"TABLE_ORDERS_PRODUCTS_ATTRIBUTES" 

具有相同的ID:

"TABLE_ORDERS_PRODUCTS"

使用的ID是:

"orders_products_id"

2 个答案:

答案 0 :(得分:2)

为了更容易阅读你的代码(所以你不需要在任何地方都有这么多的concats和引号,你可以像这样进行查询:

$sql='
select 
    op.orders_products_id, 
    op.orders_id, op.products_id,
    op.products_model, 
    op.products_name, 
    op.products_quantity,
    p.products_id 
from 
    '.TABLE_ORDERS_PRODUCTS.' op 
        left join '.TABLE_PRODUCTS.' p 
            on op.products_id = p.products_id
        left join '.TABLE_ORDERS_PRODUCTS_ATTRIBUTES.' Attrib
            on op.orders_products_id=Attrib.orders_products_id
where 
    orders_id = "' .(int)$cuttinglist['orders_id'] . '"
';
$products_query = tep_db_query($sql);

答案 1 :(得分:1)

$products_query = 
  tep_db_query("select op.orders_products_id, op.orders_id, op.products_id, ".
                  "op.products_model, op.products_name, op.products_quantity, ".
                  "p.products_id from " . TABLE_ORDERS_PRODUCTS . " op " .
              " left join " . TABLE_PRODUCTS . " p " .
              " on (op.products_id = p.products_id) "
              " left join " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " pa " .
              " on (op.products_id = pa.orders_products_id) where orders_id = '" . 
              (int)$cuttinglist['orders_id'] . "'");