1

我设法为三个表创建了一个 JOIN 查询,并且可以成功地在一个回显表中回显结果,这是我的代码:

<?php 

$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";

$result = mysql_query($sql);

if (!$result)

{

echo "An error occurred ".mysql_error();

exit;

}

echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";

while ($line = mysql_fetch_array($result)) {


$name = $line["product_name"];

$price = $line["product_price"];

$options=$line["Options_name"];

$difference=$line["Price_diff"];


echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";

}

echo "</table>\n";

?>

我的表有效,但它显示重复的条目product_name,我不知道如何删除它们。

4

1 回答 1

1

您必须在查询中使用GROUP BY子句,如下所示:

$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
        FROM ProductOptions a
        JOIN Products b ON a.product_id = b.product_id
        JOIN Options c ON a.Options_id = c.Options_id
        GROUP BY product_name
        ORDER BY product_name DESC";
于 2013-04-18T20:02:26.430 回答