【问题标题】:PHP MYSQL QUERY FETCH FROM TWO TABLES从两个表中获取 PHP MYSQL 查询
【发布时间】:2020-12-17 08:53:17
【问题描述】:

我是 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> 
';
}

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

【问题讨论】:

  • 为什么不为此使用JOIN
  • 我认为您的代码存在 SQLi 漏洞。
  • @Julia,请告诉我如何防止我的代码出现这种情况。谢谢

标签: php mysql sql join subquery


【解决方案1】:

我打算查询所有在attendance 表中没有id 作为staff_id 的员工。

您不需要两个查询加上一些 PHP 逻辑。您可以使用 not exists 在单个查询中获得所需的结果:

select s.*
from staff s
where not exists (select 1 from attendance a where a.staff_id = s.id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多