The question could have been different, like : Compare two tables in mySQL on a specific metric. My tables have a dimension (date) and a metric (number) and I want to check if I am getting the same number for the same date.
As a solution I started creating a PHP script where the table contents will be put into arrays. Then I am comparing this arrays to trace the differences.
If the number is not the same in the two tables for the same date , I will print the "date, number from table 1 - number from table 2".
Here is my code but it seems that I am having a problem with array_diff :
// Connect to the database (mySQL)
$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);
// Creation of 1st Array
$result_one = array();
// Creation of 1st SQL query
$sql = "select date, sum(number) from Table1 group by date";
// Run the 1st query
$query = $Db->query($sql);
// Save the results of the 1st query in the 1st array called result_one
$i = 0;
while ($row = $query->fetch_assoc())
{
echo "aaa";
$result_one[$i] = $row;
$i++;
}
// Print the results (array)
print_r ($result_one);
#####################################################
// Creation of 2nd Array
$result_two = array();
// Creation of 1st SQL query
$sql = "select date, sum(number) from Table2 group by date";
// Run the 1st query
$query = $Db->query($sql);
// Save the results of the 1st query in the 1st array called result_two
$i = 0;
while ($row = $query->fetch_assoc())
{
echo "aaa";
$result_two[$i] = $row;
$i++;
}
// Print the result_two (array)
print_r ($result_two);
#####################################################
// Use of array_diff
$diff = array_diff($result_one,$result_two);
// Print the differences
print_r($diff);
I am getting an error like :
PHP Stack trace:... Array to string conversion
The tables have two dimensions
You can do this with a single SQL query:
$sql = "SELECT t1.date, t1.number as `t1num`,
t2.number as `t2num`
FROM `table1` t1, `table2` t2
WHERE t1.date = t2.date AND t1.number != t2.number"
$query = $Db->query($sql);
while ($row = $query->fetch_assoc())
{
echo sprintf("mismatch: date: %s, table1: %s, table2: %s", $row['date'], $row['t1num'], $row['t2num']);
}