在php中从self join中检索行

时间:2012-12-13 18:50:14

标签: php sql

我在表中使用了self join,但是我无法检索表行

$SQL1 = "SELECT e1.userid, e2.userid
FROM userfield AS e1, userfield AS e2
WHERE e1.field5 = e2.field5 and e1.field5!=' ' and e2.field5!=' ' and e1.userid!=e2.userid";

$result2 = mysql_query($SQL1);

while ($db_field2 = mysql_fetch_assoc($result2)) {
    print $dbfield2[userid];  
}

当我执行此代码时,它只显示空白页面。当我在msql数据库中触发此查询时,它返回两个用户ID

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

$SQL1 = "SELECT e1.userid, e2.userid
    FROM userfield AS e1, userfield AS e2
    WHERE e1.field5 = e2.field5 and e1.field5!=' ' and e1.userid!=e2.userid";

$result2 = mysql_query($SQL1);

while ($db_row = mysql_fetch_assoc($result2)) {
    print $db_row['e1.userid'];  
}

P.S。您在and e2.field5!=' '子句中不需要WHERE,因为e2.field5必须等于e1.field5e1.field5!=' '

答案 1 :(得分:0)

你必须给他们这样的别名:

$SQL1 = "SELECT e1.userid AS userid1, e2.userid AS userid2
         FROM userfield AS e1, userfield AS e2
         WHERE e1.field5 = e2.field5 and e1.field5!=' ' and e1.userid!=e2.userid";

$result2 = mysql_query($SQL1);

while ($db_field2 = mysql_fetch_assoc($result2)) {
    print $dbfield2['userid1'];  
}

请考虑切换到PDO或者mysqli。所有mysql_ *函数都被正式标记为已弃用。