0

我有一点问题,我以前从未使用过 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”!虽然不知道如何发表共同声明!

4

4 回答 4

0

我认为你的问题是,MySQL 不知道如何加入这两个表。因此你必须告诉 MySQL 如何做到这一点。

例子

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

其中 col1 和 col2 是要加入的列(唯一标识符)

于 2013-10-14T10:41:53.557 回答
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'];
}

?>
于 2013-10-14T10:43:10.533 回答
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'];
于 2013-10-14T10:44:41.990 回答
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

buildings.id 是表的主键buildings

于 2013-10-14T10:47:21.773 回答