关于2个FK和1个主键的Php查询

时间:2016-05-12 19:04:55

标签: php sql

在我的表实习中,我有两个外键 id_promoter_internship id_supervisor_internship 。在表business_contacts中,我有1个主键 id_business 。我正在尝试从business_contacts表中获取数据,该表链接到实习表。以下查询是否正确?

       public function update_form_business_contact($name_enterprise){
        $query = "
             SELECT 
                  * 
             FROM business_contacts
                  ,internships 
             WHERE 
                  business_contacts.id_business = internships.id_supervisor_internship 
                  AND internships.name_enterprise_internship = '$name_enterprise'";     
        $result = $this->_db->query($query);

        # Go through results of teachers
        if($result->rowCount()!=0){
            while($row=$result->fetch()){
                $contact= new businesscontact ( $row->id_business,$row->firstname_business,$row->lastname_business,$row->service_business,$row->function_business,$row->phone_business,$row->phone_secretary_business,$row->mobile_business);
            }
        }
        return $contact;
    }

我的问题是:主键是否必须引用两个外键?如果是这样,我该怎么做呢。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您应该使用如下的连接重写查询:

func (cas CustomAttributes) MarshalXML(e *xml.Encoder,
        start xml.StartElement) (err error) {
    if len(cas.Items) == 0 {
        return nil
     }

    err = e.EncodeToken(start)
    if err != nil {
        return
    }
    err = e.Encode(cas.Items)
    if err != nil {
        return
    }
    return e.EncodeToken(xml.EndElement{
        Name: start.Name,
    })
}

答案 1 :(得分:0)

如果您需要两个ID,则使用两个ID左键连接两次:

$query = "select
               * 
          from internships i
               left join business_contacts bc  ON bc.id_business = i.id_supervisor_internship
               left join business_contacts bc2 on bc2.id_business = i.id_promoter_internship
          WHERE 
               i.name_enterprise_internship = '$name_enterprise'";

如果您只需要主管ID:

$query = "select
                   * 
              from internships i
                   left join business_contacts bc  ON bc.id_business = i.id_supervisor_internship
              WHERE 
                   i.name_enterprise_internship = '$name_enterprise'";

如果您只需要发起人ID:

$query = "select
                   * 
              from internships i
                   left join business_contacts bc on bc.id_business = i.id_promoter_internship
              WHERE 
                   i.name_enterprise_internship = '$name_enterprise'";

要在连接中使用特定参数:

$query = "select
               * 
          from internships i
               left join business_contacts bc  ON bc.id_business = i.id_promoter_internship and i.name_enterprise_internship = '$name_enterprise'";