如何比较同一MySQL表中的不同行的不同列(在php中)?

时间:2011-03-30 06:27:50

标签: php mysql compare match

我正在尝试将A行的A列与B行的B列进行比较。我怎样才能在php中执行此操作?

这是我的代码:

<?php

include("include/config.php");
include("include/functions/import.php");

$addToFriends = array();
$atf = 0;

//connect to mysql and get data for main user
mysql_connect($DBHOST,$DBUSER,$DBPASSWORD);
mysql_select_db($DBNAME);

//grabs all friend requests sent by user
$sql = "SELECT * FROM friends_requests WHERE REQUESTER = '.$_SESSION[USERID].' ";
$q = mysql_query($sql) or die(mysql_error());

$ar1 = array();
$RIDs = array();
$i=0;
while($row = mysql_fetch_array($q))
{
$ar1[] = $row[2];
$RIDs[] = $row[0];
echo "ar1".$ar1[$i];
$i++;
}

//grabs all friend requests sent to user
$sql = "SELECT * FROM friends_requests WHERE REQUESTEE = '.$_SESSION[USERID].' ";
$q = mysql_query($sql) or die(mysql_error());


$ar2 = array();
$i=0;
while($row = mysql_fetch_array($q))
{
$ar2[] = $row[1];
echo "ar2".$ar2[$i];

$i++;
}


    for($int = 0; $int < sizeof($ar1); $int++)
    {

        for($t = 0; $t < sizeof($ar2); $t++)
        {

            if($ar1[$int] == $ar2[$t])
            {
            $sql = "SELECT * FROM friends_requests WHERE RID = '.$RIDs[$int].' ";
$q = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($q))
{
            echo "lookie".$row[1];
            echo "lookie".$row[2];
            echo "/".$t;
            echo "/".$int;
                mysql_query("INSERT INTO friends (USERID,FRIENDID,time_added) VALUES ($row[1],$row[2],NOW())");
                mysql_query("INSERT INTO friends (USERID,FRIENDID,time_added) VALUES ($row[2],$row[1],NOW())");
                mysql_query("DELETE FROM friends_requests WHERE REQUESTER = $row[1] AND REQUESTEE = $row[2]");
                mysql_query("DELETE FROM friends_requests WHERE REQUESTER = $row[2] AND REQUESTEE = $row[1]");
                echo "make friends".$row[1]."b/w".$row[2];  }
            }

        }

    }


?>

目标是找到与ColumnA,RowA = ColumnB,RowB

所在地一样多的两行

1 个答案:

答案 0 :(得分:2)

这需要自我加入。假设(从您的代码中)列A是请求者,而库B是被请求者。请参阅以下示例以获取比较中的所有记录。根据您的要求调整并向查询添加更多过滤器。

select a.*,b.* from friends_requests a, friends_requests b 
where a.requester = b.requestee