2013-10-14 47 views
0

我有一個有點問題的,從未使用過香港專業教育學院在加入之前,這是第一次,我得到了一些問題:加入問題MYSQL/PHP

<?php 
//$count to keep the counter go from 0 to new value 
    $count=0; 

//I need to select the level for the users building first, meanwhile i also 
//need to get the money_gain from the table buildings, which is a table that 
//is common for each member, which means it doesnt have a userid as the other table! 
//And then for each of the buildings there will be a $counting 

    $qu1 = mysql_query("SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user"); 

    while($row = mysql_fetch_assoc($qu1)) 
    { 
    $count=$count+$row['level']; 
    echo $row['level']; 
     } 
?> 

所以基本上香港專業教育學院聽說ü應該把他們和一個共同的專欄綁在一起,但在這種情況下,他們不是任何..我現在只是失去了?

編輯哦,對,我需要用正確的money_gain取出正確的等級,在building_user的'buildingid'和建築物中,它的'id'!不知道如何做出一個共同的聲明!

+0

然後創建一個通信列像id? – bwoebi

+0

您的buildings_user表有一個與建築物表上的id綁定的building_id嗎?如果您無法添加用戶列來將它們綁定在一起,您可能能夠從中獲取一些有效的信息,因爲您的目標是該用戶的記錄。 – A23

+0

在編輯中,我確實有一個buildingid,它與建築物表上的id綁定在一起,但我在使用它們作爲條件時遇到了問題! – user2866639

回答

0

從您的編輯欄,

SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id; 
的記錄

你基本上得到在建築物加入他們的用戶ID

性能方面,連接是更好的選擇,但對於這樣的輕量級查詢,上面的查詢應該可以正常工作。

你也可以給每個列了一個更簡潔的名字

SELECT building_user.level as level,buildings.money_gain as money gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id; 

,並訪問他們作爲

$level = $row['level']; 
$gain = $row['gain']; 
+0

葉這似乎是正確的,只是一個問題,我如何保持從1-14'buildingid',因爲我需要趕上行1-14那裏呢? – user2866639

+0

您可以添加另一個AND子句。 http://dev.mysql.com/doc/refman/5.0/en/range-optimization.html SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid = $ user AND building_user.buildingid = building.id AND building.id> = 1 AND building.id <= 14; – A23

+0

哦不,我剛剛意識到這一點,我的意思是最後一個條件,它說building.id,它應該是buildings.id,現在它的工作正常!謝謝 – user2866639

0

我想你的問題是,MySQL不知道如何加入兩個表。因此,你必須告訴MySQL如何做到這一點。

SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2; 

其中col1和col2上要加入(唯一標識符)

0
<?php 

$count=0; 

$qu1 = mysql_query("SELECT bu.level, bs.money_gain FROM building_user bu, buildings bs WHERE bu.userid=$user"); 

while($row = mysql_fetch_assoc($qu1)) 
{ 
$count=$count+$row['level']; 
echo $row['level']; 
} 

?> 
+0

上面的代碼爲我工作 – Patel

0

試試這個

$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain 
        FROM building_user 
        JOIN buildings ON building_user.building_id = buildings.id 
        WHERE building_user.userid=$user"); 

building_user.building_id是表building_user

的foreght關鍵

buildings.id是表buildings的主鍵