首页 > 解决方案 > 从两个表中获取 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> 
';
}

令人惊讶的是,这会返回出勤表中的所有员工。请帮帮我

标签: phpmysqlsqljoinsubquery

解决方案


我打算进行查询以获取所有没有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)

推荐阅读