【问题标题】:Get the values of two fields from a table JOIN从表JOIN中获取两个字段的值
【发布时间】:2013-08-08 07:27:06
【问题描述】:

我有一个名为districts 的mysql 表,其中存储了所有地区及其ID。我有另一个名为 tbl_units 的表,其中保存了单元详细信息,例如 office_addressoffice_districtfactory_addressfactory_district

现在如果想通过 JOIN 两个表从他们的 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

只返回第一个,即办公室的地区名称。

【问题讨论】:

    标签: php mysql join field


    【解决方案1】:

    将区表加入单位表两次;每个区类型一次。使用别名来区分分区表的每个实例。如果您愿意,可以包含可选的 AS 关键字。

    【讨论】:

      【解决方案2】:

      试试这个也许会有帮助

      $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
      

      这里 u.id 代表区域表 id,t.id 代表 tbl_units 表 id,但在这种情况下,您的 tbl_units id 必须是外键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-10
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 2016-01-10
        • 1970-01-01
        • 2021-06-23
        相关资源
        最近更新 更多