mysql - 如何比较数据库表中具有空值的列并显示没有空值的列?

标签 mysql null

我有一个表单要求用户输入他们的员工 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

然后你可以在你的循环中得到idtype,如下:

...
$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/

相关文章:

mysql - 将oracle脚本转换为mysql脚本

xcode - IBOutlet 为零,但它在 Storyboard Swift 中已连接

sql - 当 COUNT(*) 为 NULL 时,在 GROUP BY 中返回 0

ios - NSKeyedArchiver: key 返回 nil - Swift

php - 缓慢的 WordPress 用户查询超过 7000 名用户

php - 分页之前的多维 groupBy 和 orderBy - Laravel 5

mysql - 如何用MySQL删除列中的特殊字符?

php - MySQL(和/或)PHP 问题

arrays - golang 中包含整数和 nil 值的数组?

mysql - 如果字段为空,Group_concat 不同会使我的查询失败