[英]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.