我有一个表单要求用户输入他们的员工 ID 和学生 ID。 所以如果我是学生,系统会提示我输入我的学生 ID,反之亦然。
因此现在在我的数据库后端,如果记录显示staff,将有2列显示staff_id = "abcdef"而student_id = NULL。
现在我想问一下如何比较这两列并显示没有 NULL 值的列。
现在我的当前代码没有显示任何结果也没有任何错误:
$queryID = "Select student_id, user_id FROM ID";
$resultID = mysqli_query($link, $queryID) or die(mysqli_error($link));
<table>
<th>Student/ Staff</th>
<td><?php
while ($rowID = mysqli_fetch_assoc($resultID)) {
$sid = $rowID['student_id'];
$uid = $rowID['user_id'];
if ($sid != null) {
$sid = $rowID['student_id'];
echo $sid;
} else {
$uid = $rowID['user_id'];
echo $uid;
}
}
?></td></table>
请指教和帮助。谢谢。
最佳答案
有多种解决方案,但我会将查询更改为:
Select IFNULL(student_id, user_id) as ID,
CASE WHEN student_id IS NULL THEN 'User'
ELSE 'Student'
END as Type
FROM ID
CASE WHEN ... Type
是可选的,以防您仍然想知道您得到的是哪种 id
。
然后你可以在你的循环中得到id
和type
,如下:
...
$id = $rowID['id']; // for either student or user
$type = $rowID['type']; // either "User" or "Student"
而且您不再需要 if
语句。
我添加了变量 $type
,因为您可能仍然想知道它是两者中的哪一个,但如果您只需要显示这一列,则您并不需要它。
因此,在修复了一些缺少 tr
标签的其他问题后,假设您不需要 $type
,您会得到:
$queryID = "Select IFNULL(student_id, user_id) as ID FROM ID";
$resultID = mysqli_query($link, $queryID) or die(mysqli_error($link));
<table>
<tr><th>Student/ Staff</th></tr>
<?php
while ($rowID = mysqli_fetch_assoc($resultID)) {
echo "<tr><td>{$rowID['id']}</td></tr>";
}
?>
</table>
关于mysql - 如何比较数据库表中具有空值的列并显示没有空值的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34107778/