[英]mysql php 5 table joins
Still learning about MySQL joins at the moment. 目前仍在学习MySQL连接。 On one page of my site it shows an inventory, and it needs to pull data from 5 tables to form it. 在我网站的一页上,它显示了一个清单,并且需要从5个表中提取数据以形成清单。
Currently i do this: (yes its shoddy) 目前我正在这样做:(是次充好)
$sql_result4 = mysql_query("SELECT * FROM players WHERE id='$id'", $db);
$rs4 = mysql_fetch_array($sql_result4)
if ($rs4[firearm] != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_firearms WHERE name='$rs4[firearm]'", $db);
$rs5 = mysql_fetch_array($sql_result5); $firearm_icon=$rs5[icon]; $weap = $rs4[firearm];
}
if ($rs4[accessory2] != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_items WHERE name='$rs4[accessory2]'", $db);
$rs5 = mysql_fetch_array($sql_result5); $item_icon=$rs5[icon]; $access = $rs4[accessory2];
}
if ($rs4[vehicle2] != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_vehicles WHERE name='$rs4[vehicle2]'", $db);
$rs5 = mysql_fetch_array($sql_result5); $veh_icon=$rs5[icon]; $veh = $rs4[vehicle2];
}
if ($rs4[melee2] != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_melee WHERE name='$rs4[melee2]'", $db);
$rs5 = mysql_fetch_array($sql_result5); $mel_icon=$rs5[icon]; $mel = $rs4[melee2];
}
As you can see, this is stupid. 如您所见,这很愚蠢。 I'm guessing I need to combine all that into one, haven't a clue where to start. 我猜想我需要将所有这些结合在一起,不知道从哪里开始。
SELECT *, db_firearms.icon as firearm_icon, db_items.icon as item_icon, db_vehicles.icon as vehicle_icon, db_melee.icon as melee_icon
FROM players
LEFT JOIN db_firearms ON (db_firearms.name=firearm)
LEFT JOIN db_items ON (db_items.name=accessory2)
LEFT JOIN db_vehicles ON (db_vehicles.name=vehicle2)
LEFT JOIN db_melee ON (db.melee.name=melee2)
WHERE players.id = $id
Make sure the name field is indexed in all of the tables 确保名称字段已在所有表中建立索引
i advice you to find a better way then to do 4 JOINS. 我建议您找到一种更好的方法,然后再做4次加入。
because you are multiplying the run time very much. 因为您将大大增加运行时间。
let say you have 1000 rows in each table (which is not a lot) 假设每个表中有1000行(不是很多)
the Cartesian multiply will be 1000 * 1000 * 1000 * 1000 * 1000 which is 1000000000000000 , this is the size of the table the server needs to process. 笛卡尔乘将是1000 * 1000 * 1000 * 1000 * 1000,即1000000000000000,这是服务器需要处理的表的大小。
avoid JOINS at all costs 不惜一切代价避免加入
That's not so stupid as it seems. 看起来并不那么愚蠢。 I would change only connected-tables-primary keys from name to id. 我只将连接表主键从名称更改为ID。 So you select player and it has firearm_id, accessory_id, vehicle_id and so on. 因此,您选择播放器,它具有firearm_id,accessory_id,vehicle_id等。 Theese ids are usually numbers. Theese ID通常是数字。 Also this case it's simply to add many-to-many associations if You need. 同样,在这种情况下,如果需要,只需添加多对多关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.