'Showing all results also when not present in 2nd optional database

An explaination of how my code works: I have a pure select on a database that is filled through a different program. I am selecting data to check up on orders. Now I want to give a ready status to the order, which cannot be inserted into the database I am selecting from, so I created a small different database to insert the ordernumber (from the previous selection) into that database and insert a 1. This can be updated to a 0 by pressing the button again.

Now I want to show my orders as the following:

An order can have the status, but doesn't have to have a status. If it doesnt have a status it should show in the list. With my current code (below) it only shows orders that are present in the 2nd optional database, I understand why this is happening. But I can't manage to work out a solution to show everything even if an ordernumber is not present in the 2nd optional database.

while( $row = sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) ) {
    $statusorder = $row['ordernr'];  //Ordernumber selected in primary database
    $sqlstatus = "SELECT status from status WHERE Ordernr = '$statusorder'"; //selecting the status from optional database
    $result = $conn2->query($sqlstatus);
    while($row2 = $result->fetch_assoc()) {
        <insertmyhtmlhere>
    }
}
php


Solution 1:[1]

You can use only one query to get all data. Just use database.Table.column

This will display all order id of table database1.ordersTable

SELECT db1.id FROM database1.`ordersTable` db1

This will display all status of table database2.statusTable

SELECT db2.status FROM database2.`statusTable` db2

Now just combine with LEFT JOIN to show all rows whether it exists or not.

SELECT  db1.id, db2.`status` 
FROM  database1.`ordersTable` db1  
LEFT JOIN database2.`statusTable` db2
ON db1.`id` = db2.`status`;

Don“t forget to use Condition to filter, in this case, the same order id.

ON db1.`id` = db2.`status`;

If databases haves different COLLATION you can use this:

SELECT  db1.`id', db2.`status` 
FROM  database1.`ordersTable` COLLATE utf8mb4_spanish_ci db1
LEFT JOIN database2.`statusTable` COLLATE utf8mb4_spanish_ci db2
ON db1.`id` = db2.`status`;

Here are a sample fiddle

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1