2012-09-05 113 views
0

我有以下查詢:加入左多個表加入

$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兩個表在一起。如何將我加入一個名爲第三表:

"TABLE_ORDERS_PRODUCTS_ATTRIBUTES" 

用相同的ID爲:

"TABLE_ORDERS_PRODUCTS" 

所用的ID是:

"orders_products_id" 

回答

2

爲了便於閱讀你的代碼(所以你不需要有這麼多的連接和引號,你可以做任何查詢,如:

$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

TABLE_ORDERS_PRODUCTS amd TABLE_PRODUCTS是PHP常量,所以您確實需要這些引號(或以其他方式替換它)。 – Sherlock

+0

@ Robinv.G。是的,好點,更新了答案。 +1 – Fluffeh

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'] . "'");