查询多个SQL表

时间:2013-09-09 12:22:01

标签: php mysql sql

我需要查询多个表中的值,并确保结果显示正确。

每个表都有唯一的product_id,但如何确保数据正确排列?例如,从不同的表中查询product_price,并且需要与正确的产品对齐。

我是SQL的新手,所以如果这很容易就道歉。


$query = "SELECT * FROM jos_vm_product ORDER BY product_publish DESC";
$result = mysql_query($query);

echo "<table>";
while($row = mysql_fetch_array($result)){

echo "<tr><td>" . $row['product_id'] . "</td><td>" . $row['product_sku'] . "</td><td>" . $row['product_name'] . "</td><td>" . $row['product_in_stock'] . "</td><td>" . $row['product_sales'] . "</td><td>" .  $row['product_price'] . "</td><td>" . $row['product_available_date'] . "</td><td>" . $row['product_publish'] . "</td></tr>";

}

echo "</table>";

2 个答案:

答案 0 :(得分:0)

进行连接(INNER JOIN或LEFT JOIN,具体取决于表缺少匹配行时会发生什么):

SELECT * FROM jos_vm_product 
  INNER JOIN <second product table> on jos_vm_product.product_id = <second product table>.product_id
  INNER JOIN <third product table> on jos_vm_product.product_id = <third product table>.product_id
ORDER BY jos_vm_product.product_publish DESC

答案 1 :(得分:0)

SELECT * FROM jos_vm_product ORDER BY product_publish DESC

上面的查询对我来说看起来只是从1个表或视图中获取。在这种情况下,您不是从多个表中选择...

但是举个例子,你可以使用JOIN作为@Matt.C建议。

SELECT * -- select everything from P and PS you can specify (P.ID, PS.productPrice)
FROM jos_vm_product P
INNER JOIN jos_vm_productPrices PS -- join to another table.
ON P.ProductID = PS.ProductID -- join on what?
ORDER BY P.product_publish DESC