PHP 使用 PDO 和两个数据表

PHP using PDO with two data tables

我希望状态栏在device_transactionstable中没有对应的记录或者device_transactions中有对应的记录时显示值“free”table 与 returned_date 空白字段

我想要的return结果是这样的

这就是我现在能做的

device_transactions table 在设备 table 中没有相应记录时,如何打印第 4 行?

2条数据tables

Table 设备:

id name
1 Laptop01
2 Laptop02
3 Laptop03
4 Laptop04

Table device_transactions:

id device_id start_transaction_plan end_transaction_plan returned_date
1 1 2021-12-10 14:20:43 2021-12-12 07:00:00 2021-12-12 9:30:23
2 2 2021-12-11 10:10:20 2021-12-15 15:30:00 2021-12-16 7:30:45
3 3 2021-12-12 19:03:00 2021-12-21 08:00:00 NULL
<table id="myTable">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody> 
            <?php
                    $sql = $conn->prepare("SELECT devices.id, devices.name, device_transactions.returned_date 
                         FROM devices, device_transactions WHERE devices.id = device_transactions.device_id ");
                    $sql->execute();
                    $result = $sql->setFetchMode(PDO::FETCH_ASSOC);
                    foreach ($sql->fetchAll() as $row) { ?>
                    <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo $row['name']; ?></td>
                            <td><?php                             
                                if($row['returned_date'] !== null ){
                                    echo "free";
                                }
                                else{
                                    echo "borrowed";
                                }
                            ?></td>
                    </tr>
                    <?php } 
            ?>
        </tbody>    
                
    </table>

您想使用 LEFT JOIN,而不是 FROM devices, device_transactions(这是一个 INNER JOIN)。

SELECT devices.id, devices.name, device_transactions.returned_date 
FROM devices
LEFT JOIN device_transactions ON devices.id = device_transactions.device_id

只需使用简单的 LEFT JOIN 即可获得所有记录:

好的,我做了一些修改,所以我的答案与已经给出的答案不同,这将帮助您避免在 return 日期是否为 null 时检查

SELECT d.id as deviceid, d.name as devicename, c.returned_date as returndate
FROM device d
LEFT JOIN device_transactions c ON c.device_id = d.id;

编辑查询 - 所以现在如果没有记录或 return 日期为空,您将获得 'free' 作为 returntype 否则您将获得 'borrowed' (你当然可以放任何你想要的东西......)所以现在不需要在 php 中检查 $row['return_date'] == null 是否只是输出查询的结果:

SELECT d.id as deviceid, d.name as devicename,
CASE WHEN c.returned_date IS NULL THEN 'free' ELSE 'borrowed' END as returntype
FROM device d
LEFT JOIN device_transactions c ON c.device_id = d.id;

看到它在这里工作

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=32db15fbb2b00d780196ea879e6f7d20

编辑结果:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4edc860aa39461f2c5e6655bbca77d66