简体   繁体   中英

join issue MYSQL/PHP

i have a bit of a problem, ive never used JOIN before, and this is the first time, and i got into some problems:

<?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'];
        }
?>

So basically ive heard that u should tie them together with a common column but, in this case thir isnt any.. im just lost right now?

EDIT Oh right, I need the right level to be taken out with the correct money_gain too, in building_user its 'buildingid'and in buildings, its just 'id'! have no idea how to make a common statement though!

i think you problem is, that MySQL doesn't know how to JOIN the two Tables. Therefor you have to tell MySQL how to do that.

Example

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

where col1 and col2 are the columns to join (a unique identifier)

<?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'];
}

?>

From your edit,

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

You essentially get the records for the user joining them at the building id

Performance-wise, joins are a better choice but for lightweight queries such as this, the query above should work fine.

You can also give each column a neater name

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;

and access them as

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

Try this

$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 is the foreght key of table building_user and

buildings.id is the primary key of table buildings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM