[英]PHP MYSQL QUERY FETCH FROM TWO TABLES
Please I'm new to PHP/MYSQL.请我是 PHP/MYSQL 的新手。 I have two tables.
我有两张桌子。 Table staff has (id, fullname) and Table attendance has (id,staff_id).
表员工有(id,全名)和表出勤有(id,staff_id)。 I intend to make a query to fetch all staff staff who do not have their id as staff_id in Attendance table.
我打算进行查询以获取所有在出勤表中没有将其 id 设为 staff_id 的员工。 Below is my PDO code:
下面是我的 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>
';
}
Surprisingly, this returns all staffs present in the Attendance table.令人惊讶的是,这会返回出勤表中存在的所有员工。 Please help me out
请帮帮我
I intend to make a query to fetch all staff who do not have their
id
asstaff_id
inattendance
table.我打算进行查询以获取所有在
attendance
表中没有将其id
设为staff_id
员工。
You don't need two queries plus some PHP logic for this.为此,您不需要两个查询加上一些 PHP 逻辑。 You can get the result that you want in a single query, using
not exists
:您可以在单个查询中获得所需的结果,使用
not exists
:
select s.*
from staff s
where not exists (select 1 from attendance a where a.staff_id = s.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.