连接具有不同ID的多个表

时间:2012-09-03 16:22:13

标签: php mysql sql join

我有以下查询:

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

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

"TABLE_ORDERS_PRODUCTS_ATTRIBUTES" 

具有相同的ID:

"TABLE_ORDERS_PRODUCTS"

使用的ID是:

"orders_products_id"

2 个答案:

答案 0 :(得分:5)

只需添加另一个连接子句:

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 ...

答案 1 :(得分:0)

$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 );