mysql - 从其他表中选择用户名,如果为 NULL

标签 mysql

如何从 users 表中选择行条目,如果另一个表有一个 NULL 值?

SELECT
    CONCAT(`fh_users`.`username`, '_', `fh_ftp_user`.`username`) AS `userid`,
    `fh_ftp_user`.`password` AS `passwd`,
    '1010' AS `uid`,
    '1010' AS `gid`,
    `fh_ftp_user`.`path` AS `homedir`,
    '/sbin/nologin' AS `shell`
FROM
    `fh_ftp_user`,
    `fh_users`
WHERE
    `fh_ftp_user`.`username`='%U'
    OR
    (`fh_ftp_user`.`user_id`=`fh_users`.`id` AND `fh_users`.`username`='%U' AND `fh_ftp_user`.`username` IS NULL)"

隐含的,表 fh_ftp_user 将被选中。 fh_users 将仅用于CONCAT 用户名与主用户名。

用户表

enter image description here

FTP 用户

enter image description here

结果

enter image description here

预期结果

如果fh_ftp_user.usernameNULL,设置fh_users.usernameuserid 否则,如果 fh_ftp_user.username不是 NULL,则将两个用户名与下划线连接为 userid

我如何在这里创建一个子查询来处理这些行为?

最佳答案

使用 CASE你可以处理这种情况:

 SELECT
     CASE WHEN fh_ftp_user.username IS NULL THEN fh_users.username
          ELSE CONCAT(`fh_users`.`username`, '_', `fh_ftp_user`.`username`) 
          END AS `userid`,
     ....

关于mysql - 从其他表中选择用户名,如果为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985014/

相关文章:

java - 如何将字符串返回为json格式

mysql - 有趣的 sql 查询(不在 select 中)

仅当行数大于零时,mysql 查询才返回

mysql - 无法安装适用于 Python 3 的 mysql 连接器

mysql - 如果在另一个表上匹配,则排除一个表中的行 - MySql

MySQL 查询速度或行读取

mysql - 如何在sql中维护队列号

MySQL:何时分解/分割表

PHP Get 方法不起作用

mysql - 使用 AJAX 更新数据库