2011-03-30 146 views
1

我想比較行A的列A和行B的列B.我怎麼能去做這個在PHP?如何比較同一個MySQL表中不同行的不同列(在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,樂華= ColumnB,rowB中

回答

2

這將需要一個自我加入。假設(從您的代碼)列A是請求者,並且coumn B是請求者。請參閱以下示例以獲取比較中的所有記錄。根據您的要求調整併爲查詢添加更多過濾器。

select a.*,b.* from friends_requests a, friends_requests b 
where a.requester = b.requestee 
相關問題