[英]join issue MYSQL/PHP
我有一個問題,我以前從未使用過JOIN,這是第一次,我遇到了一些問題:
<?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”! 不知道如何發表共同聲明!
我認為您的問題是,MySQL不知道如何聯接兩個表。 因此,您必須告訴MySQL如何做到這一點。
例
SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2;
其中col1和col2是要連接的列(唯一標識符)
<?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'];
}
?>
根據您的修改,
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'];
嘗試這個
$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
的前鍵,並且
buildings.id
是餐桌buildings
的主鍵
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.