I have a mysql table called districts
where all the districts and their id's are stored. I have another table called tbl_units
where unit details such as office_address
, office_district
, factory_address
, factory_district
are saved.
我有一个名为区的mysql表,其中存储了所有区域及其ID。我有另一个名为tbl_units的表,其中保存了office_address,office_district,factory_address,factory_district等单元详细信息。
Now if want to get the names of the districts from their id's by JOIN ing the two tables, how should I write the query ? Because
现在,如果想通过加入两个表来从他们的id获取区域的名称,我应该如何编写查询?因为
SELECT u.*, d.district_name
FROM tbl_unit_details as u,
tbl_districts as d
WHERE u.unit_id = '$unit_id'
AND u.district_id = d.district_id
AND u.factory_district_id = d.district_id
ORDER BY unit_name
returns only the first , i.e. district name of office.
只返回第一个,即地区的办公室名称。
2 个解决方案
#1
0
Join the districts table to the units table twice; once for each district type. Use aliases to distinguish each instance of the district table. If you like, you can include the optional AS
keyword.
将区域表加入单位表两次;每个地区类型一次。使用别名来区分分区表的每个实例。如果您愿意,可以包含可选的AS关键字。
#2
0
try this out maybe it can help
试试这个也许它可以帮助
$sql=mysql_query("SELECT u.*,t.* FROM districts as u,tbl_units as t WHERE u.id=t.id");
$row=mysql_fetch_array($sql);
//echo your required result however you want
here u.id represents districs table id and t.id represents tbl_units table id, but in this case your id for tbl_units must be a foreign key.
这里u.id表示districs表id,t.id表示tbl_units表id,但在这种情况下,tbl_units的id必须是外键。
#1
0
Join the districts table to the units table twice; once for each district type. Use aliases to distinguish each instance of the district table. If you like, you can include the optional AS
keyword.
将区域表加入单位表两次;每个地区类型一次。使用别名来区分分区表的每个实例。如果您愿意,可以包含可选的AS关键字。
#2
0
try this out maybe it can help
试试这个也许它可以帮助
$sql=mysql_query("SELECT u.*,t.* FROM districts as u,tbl_units as t WHERE u.id=t.id");
$row=mysql_fetch_array($sql);
//echo your required result however you want
here u.id represents districs table id and t.id represents tbl_units table id, but in this case your id for tbl_units must be a foreign key.
这里u.id表示districs表id,t.id表示tbl_units表id,但在这种情况下,tbl_units的id必须是外键。