提问者:小点点

PHP使用PDO和两个数据表


device_transactions表中没有相应的记录,或者在device_transactions表中有相应的记录时,我希望状态列显示值“自由”returned_date空白字段

device\u transactions表在devices表中没有相应的记录时,如何打印第4行?

这两个数据表

表设备:

表1设备\u事务:

<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>

共2个答案

匿名用户

您希望使用左连接,而不是来自设备、设备\u事务的(这是一个内部连接)。

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

匿名用户

只需使用简单的左连接,您将获得所有记录:

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;

看到它在这里工作了吗

https://dbfiddle.uk/?rdbms=mysql_8.0