PHP & MySQL如何從一個表中檢索多個記錄和從另一個表中檢索相應記錄並將它們一起顯示。php和mysql如何加入表
我有一個代碼,它將表中所有公司的所有購買價值(交易)相加,並顯示與公司代碼(buy_firm_code)相對應的值。我有另一個表(client_firm),它包含我所有的公司和他們的代碼。公司名稱字段被稱爲firm_name,而公司代碼字段稱爲firm_code,它是交易表buy_firm_code字段的主要字段。我想從client_firm表中檢索firm_name,並將其顯示在我從交易表中檢索到的相應buy_firm_code中。我如何編寫PHP代碼的第二部分。提前致謝。
<?php
//code that sums all the purchase value of all firms in my table (trades) and displays the value against the firm code(buy_firm_code)
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$buy_firm_code="";
$buy_value="";
$sql="SELECT buy_firm_code, SUM(trade_value) value_bought FROM trades GROUP BY buy_firm_code ORDER BY value_bought DESC";
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while($row=mysqli_fetch_array($result)){
$buy_firm_code=$row['buy_firm_code'];
$buy_value = $row['value_bought'];
echo $buy_firm_code.'<-->'.$buy_value .'<br>';
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
你爲什麼不想要在SQL查詢中加入結果? – ToothlessRebel