关于2个FK和1个主键

时间:2016-05-12 19:45:23

标签: php sql foreign-keys

在我的表实习中,我有两个外键 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;
}

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

3 个答案:

答案 0 :(得分:0)

你应该使用JOIN(因为那是FK的用途)。 JOIN语法告诉DB如何关联表(并使其他任何处理代码的人都清楚)。顺便提一句,您应该避免SELECT *并列出您想要的字段。

SELECT bc.*, i.* 
FROM 
    business_contacts bc
        INNER JOIN internships i ON bc.id_business = i.id_supervisor_internship 
WHERE 
    i.name_enterprise_internship = '$name_enterprise'

您只需要引用相关的字段。在您写入数据时强制执行FK。

答案 1 :(得分:0)

您正试图从internships获取数据,因此启动

SELECT *
FROM internships

这为您提供实习机会,其中包括联系人的标识符。要为这些联系人添加信息,请加入包含该信息的表。在这种情况下,有两个连接,每个联系一个:

SELECT *
FROM internships
INNER JOIN business_contacts promoter
  ON internships.id_promoter_internship = promoter.id
INNER JOIN business_contacts supervisor
  ON internships.id_supervisor_internship = supervisor.id

通过提供表别名(在这种情况下为promotersupervisor),您可以轻松地连接同一个表两次(或者您想要的次数,真的)并将其视为单独的表

结果是internships中的所有记录以及business_contacts中与internships记录中每个键相关的其他数据。

您还可以对列进行别名,以使结果更加明确。类似的东西:

SELECT
    internships.some_field AS some_field,
    promoter.some_field AS promoter_some_field,
    supervisor.some_field AS supervisor_some_field
FROM
...

答案 2 :(得分:0)

不是很糟糕,但你可能想试试这个:

    <?php

    public function update_form_business_contact($name_enterprise){
        $query = "
                 SELECT
                      *
                 FROM business_contacts bCon
                 INNER JOIN internships  iShip
                 ON bCon.id=iShip.id_supervisor_internship
                 WHERE
                     iShip.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;
    }