How to match two table columns in sql

I have this code

$db = \Config\Database::connect();  $query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;"); foreach ($query->getResult() as $g) {     $g_amount = $g->g_amount;  }  $query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;"); foreach ($query2->getResult() as $p) {     $p_amount = $p->p_amount;  }  if($p_amount ==  $g_amount){  echo "do something";  }else{  echo "No match"; } 

Here I am trying to match between table g and table p…. if any column in table g is == any column in table p regardless of the number of column, do something but it always echo "NO match"

I put "Limit 10" in case there is much number of rows in the table, it will only match the first 10th row with the "ordering" command.

Please I need some help.

Add Comment
2 Answer(s)

First, get data as an array

$db = \Config\Database::connect(); $query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;"); $g_results = $query->getResult('array');  $g_amounts = array_column($g_results,'g_amount');  $query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;"); $p_results = $query2->getResult('array');  $p_amounts = array_column($p_results,'p_amount');  foreach(array_intersect($g_amounts,$p_amounts) as $amount){    echo "do something"; } 
Add Comment

Why not use a JOIN and see if it returns something? Not sure if my syntax is correct, I don’t do JOINs very often:

SELECT * FROM g g_table JOIN p p_table ON g_table.g_amount = p_table.p_amount WHERE g_table.status = '0' AND p_table.status = '0'

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.