php - 从两个表中获取 PHP MYSQL 查询
问题描述
请我是 PHP/MYSQL 的新手。我有两张桌子。餐桌员工有(id,全名),餐桌出勤有(id,staff_id)。我打算进行查询以获取所有在出勤表中没有其 id 作为 staff_id 的员工。以下是我的 PDO 代码:
$att = $con->prepare('SELECT member_id FROM attendance');
$att->execute();
while ($att_fetch = $att->fetch()) {
$absent = $con->prepare('SELECT * FROM members WHERE id != "'.$att_fetch['member_id'].'" ');
$absent->execute();
$absent_fetch = $absent->fetch();
echo '
<tr>
<td class="name" data-id="'.$absent_fetch['id'].'">'.ucwords($absent_fetch['fullname']).'</td>
</tr>
';
}
令人惊讶的是,这会返回出勤表中的所有员工。请帮帮我
解决方案
我打算进行查询以获取所有没有
id
在表中staff_id
的员工。attendance
为此,您不需要两个查询以及一些 PHP 逻辑。您可以使用以下命令在单个查询中获得所需的结果not exists
:
select s.*
from staff s
where not exists (select 1 from attendance a where a.staff_id = s.id)
推荐阅读
- c# - 使用 MVC 中的“DropDownListFor”将下拉选择值从视图发送到控制器
- javascript - 角度下拉切换和 closeOutside
- python - 使用域属性并排绘制 3 个饼图
- php - 如何更改 WooCoomerce 预订中的“预订成本”文本
- python - 如何在 Pandas 中用 df.apply() 替换 df.iterrows()?
- sql - 在 Oracle ALL_CONSTRAINTS 中仅查找用户定义的检查约束
- c - 这是检查可变参数宏参数列表是否为空的有效方法吗?
- reactjs - 在 Draft JS 中显示图像文件上传的问题
- angular - Angular Material 主题只有浅色还是深色?
- objective-c - 将 objc 块传递给函数