mariadb 如何在MySQL视图中返回无结果的值?

cidc1ykv  于 2022-11-08  发布在  Mysql
关注(0)|答案(1)|浏览(184)

我有一些由视图生成的MySQL记录:

+---------+-----------------------------+------------+
| user_id | meta_key                    | meta_value |
+---------+-----------------------------+------------+
|       2 | admin-first-timer-training  | NULL       |
|       2 | admin-first-timer-overnight | No         |
|       2 | admin-first-timer-outdoor   | No         |
+---------+-----------------------------+------------+

我要有记录:

+---------+-----------------------------+------------+
| user_id | meta_key                    | meta_value |
+---------+-----------------------------+------------+
|       2 | admin-first-timer-training  | Yes        |
|       2 | admin-first-timer-overnight | No         |
|       2 | admin-first-timer-outdoor   | No         |
+---------+-----------------------------+------------+

目前,我正在使用此视图生成这些记录:

create VIEW `wp_record_db` AS 
select distinct `u`.`ID` AS `id`,
    (select distinct (
        CASE WHEN `wp_usermeta`.`meta_value`="No" THEN "No" 
              ELSE "Yes" END) 
    from `wp_usermeta` 
    where `wp_usermeta`.`user_id` = `u`.`ID` and `wp_usermeta`.`meta_key` in ('admin-first-timer-outside','admin-first-timer-outdoors','admin-first-timer-outdoor') 
    limit 1) AS `admin-first-timer-outdoor`,
    (select distinct (
        CASE WHEN `wp_usermeta`.`meta_value`="No" THEN "No" 
             WHEN `wp_usermeta`.`meta_value` IS NULL THEN "YES" 
             ELSE "Yes" END) 
    from `wp_usermeta` where `wp_usermeta`.`user_id` = `u`.`ID` and `wp_usermeta`.`meta_key` = 'admin-first-timer-training' 
    limit 1) AS `admin-first-timer-training`,
    (select distinct (
        CASE WHEN `wp_usermeta`.`meta_value`="No" THEN "No" 
             ELSE "Yes" END) 
    from `wp_usermeta` 
    where `wp_usermeta`.`user_id` = `u`.`ID` and `wp_usermeta`.`meta_key` = 'admin-first-timer-overnight' 
    limit 1) AS `admin-first-timer-overnight` 
from `wp_users` `u`;

如您所见

(select distinct (CASE WHEN `wp_usermeta`.`meta_value`="No" THEN "No" WHEN `wp_usermeta`.`meta_value` IS NULL THEN "YES" ELSE "Yes" END) from `wp_usermeta` where `wp_usermeta`.`user_id` = `u`.`ID` and `wp_usermeta`.`meta_key` = 'admin-first-timer-training' limit 1) AS `admin-first-timer-training`,

我一直在尝试使用Case语句测试它是否为NULL,但是这并没有提供所需的结果。

SELECT IFNULL((select `wp_usermeta`.`meta_value` from `wp_usermeta` where `wp_usermeta`.`user_id` = 2 and `wp_usermeta`.`meta_key` = 'admin-first-timer-training'), "Yes");

是我所能得到的最接近的--因为这看起来确实产生了所需的返回输出,但我不能使它在Case语句中工作--无论我如何尝试插入它,它总是返回一个Empty语句。
我可以尝试什么?

gblwokeq

gblwokeq1#

您可以使用条件聚合使查询表可读
但是NULL始终与不相同,因此不需要对NULL进行额外检查
第一个

  • db〈〉小提琴

相关问题