2015-07-02 27 views
-1

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

?> 
+0

你爲什麼不想要在SQL查詢中加入結果? – ToothlessRebel

回答

1

sql查詢更改這個

$sql="SELECT t.buy_firm_code, f.firm_name, SUM(t.trade_value) value_bought 
    FROM trades t,client_firm f 
    WHERE f.firm_code = t.buy_firm_code 
    GROUP BY buy_firm_code ORDER BY value_bought DESC"; 

while塊這個

while($row=mysqli_fetch_array($result)) { 
    $buy_firm_code=$row['buy_firm_code']; 
    $buy_value = $row['value_bought']; 
    $firm_name = $row['firm_name']; 
    echo $buy_firm_code.'<-->'.$firm_name.'<-->'.$buy_value .'<br>'; 
} 

,讓我知道,如果它顯示你所需要

+0

非常感謝你們。我會在今天晚些時候嘗試'WHERE'和'JOIN'選項,並讓你知道它是如何發生的。 – Gyne

+0

再次感謝你們。 「Where」和「JOIN」都很好地工作。我正面臨着一個新的挑戰,儘管我希望在嘗試最好的時候發佈這個新挑戰。 – Gyne

+0

歡迎您,請將答案標記爲已接受,如果它適合您 –