简体   繁体   中英

Joining multiple tables with different ID's

I have the following query:

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

This joins two tables together with the same id. How would I join a 3rd table called:

"TABLE_ORDERS_PRODUCTS_ATTRIBUTES" 

with the same id as:

"TABLE_ORDERS_PRODUCTS"

The ID used is:

"orders_products_id"

Simply add another join clause:

SELECT ...
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 ...
$sql  = " select ";
$sql .= "   op.orders_products_id,  op.orders_id,          op.products_id,  op.products_model, ";
$sql .= "   op.products_name,       op.products_quantity,  p.products_id ";
$sql .= " from ". TABLE_ORDERS_PRODUCTS ." op ";   
$sql .= " left join ". TABLE_PRODUCTS ." p on (op.products_id = p.products_id) ";
$sql .= " left join ". TABLE_ORDERS_PRODUCTS_ATTRIBUTES ." pa on (pa.orders_products_id = op.orders_products_id) ";
$sql .= " where op.orders_id = ";
$sql .= "'". (int)$cuttinglist['orders_id'] ."'";

$cuttinglist_products_query = tep_db_query( $sql );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM