在MySQL中选择具有相同名称的多个列

时间:2012-10-09 18:33:10

标签: mysql sql

我想在mysql中访问两个表,并希望使用两个表中的字段。我使用内部连接来匹配两个表,但想知道如何在两个表中获取字段,因为两个表都具有相同的字段名称和不同的值。 这是我的询问......

$query1 = mysql_query("SELECT facilitator.FacID, facilitator.email, assigned.email FROM facilitator INNER JOIN assigned ON facilitator.FacID = assigned.FacID WHERE assigned.email = '$stuemail' AND facilitator.active = '1'") or die($query."<br/><br/>".mysql_error());
            while($line1=mysql_fetch_array($query1,MYSQL_ASSOC)){
                $faci= $line1['FacID'];
                $facemail = $line1['email'];
                $stumail2 = $line1['email'];
.............code goes on.............. 

我想获取两个电子邮件字段值,但想知道该怎么做。我确信我为$ stumail2所写的内容是错误的。请帮我。

3 个答案:

答案 0 :(得分:1)

您有几个选择。

第一个是在MySQL中分配字段别名:

SELECT
    facilitator.FacID,
    facilitator.email AS facilitatorEmail,
    assigned.email AS assignedEmail
    ....

第二个,因为您使用mysql_fetch_array(),是按索引访问字段。 facilitator.email字段的索引为1assigned.email的索引为2,因此您可以使用:

$facemail = $line1[1];
$stumail2 = $line1[2];

或者,默认情况下,MySQL 应该为每个重复的列名添加一个增量编号(从1开始)。因此,您应该可以使用email1访问assigned.email列:

$facemail = $line1['email'];
$stumail2 = $line1['email1'];

答案 1 :(得分:0)

您可以在列上使用别名来消除它们的歧义,例如:

SELECT facilitator.FacID, 
    facilitator.email as FacilitatorEmail, 
    assigned.email as AssignedEmail
FROM ...

答案 2 :(得分:0)

您只需在查询中使用'as'关键字:

$query1 = mysql_query("SELECT facilitator.FacID, facilitator.email as fac_email, assigned.email as assign_email FROM facilitator INNER JOIN assigned ON facilitator.FacID = assigned.FacID WHERE assigned.email = '$stuemail' AND facilitator.active = '1'") or die($query."<br/><br/>".mysql_error());
        while($line1=mysql_fetch_array($query1,MYSQL_ASSOC)){
            $faci= $line1['FacID'];
            $facemail = $line1['fac_email'];
            $stumail2 = $line1['assign_email'];