Get the values of two fields from a table JOIN

本小妞迷上赌 提交于 2019-12-14 03:14:51

问题


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.

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

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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18120256/get-the-values-of-two-fields-from-a-table-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!