繁体   English   中英

MySQL-仅在具有值的情况下选择列

[英]MySQL - SELECTING COLUMNS ONLY IF THEY HAVE VALUES

我需要构建一个MySQL查询,其中仅当它具有给定的4个列first_accuracysecond_accuracythird_accuracyfourth_accuracy具有值(不是NOT NULL )时才需要选择列。

假设我只有first_accuracysecond_accuracy的值,那么查询应该是

从Compliance_employees CE中选择first_accuracy,second_accuracy。

更新:

我套用的查询:

SELECT first_accuracy, second_accuracy, third_accuracy, fourth_accuracy FROM compliance_employees CE;

结果:

在此处输入图片说明

您可能会看到,对于“第三精度”,任何行都没有值,因此我根本不想选择该列。 那可能吗?

有什么办法吗?

如果您只想确保两列first_accuracysecond_accuracy不为NULL使用以下命令:

SELECT first_accuracy,
       second_accuracy
FROM compliance_employees CE
WHERE first_accuracy  IS NOT NULL AND
      second_accuracy IS NOT NULL

如果要确保所有四个列都不为NULL使用以下命令:

SELECT first_accuracy,
       second_accuracy
FROM compliance_employees CE
WHERE first_accuracy  IS NOT NULL AND
      second_accuracy IS NOT NULL AND
      third_accuracy  IS NOT NULL AND
      fourth_accuracy IS NOT NULL

使用'UNION',GROUP_CONCAT()和'not null',我们找到具有值的列数。 然后将列传递给“准备的陈述”,从而为您提供所需的结果。

        select coalesce (GROUP_CONCAT(col_name),'No_Result') into @ColumnNames
        from (
        select 'first_accuracy' as col_name, count( distinct first_accuracy) as count from compliance_employees
        where first_accuracy  is not null 
        union
        select 'second_accuracy' as col_name, count( distinct second_accuracy) from compliance_employees
        where second_accuracy  is not null
        union
        select 'third_accuracy' as col_name, count( distinct third_accuracy) from compliance_employees
        where third_accuracy  is not null
        union
        select 'fourth_accuracy' as col_name, count( distinct fourth_accuracy) from compliance_employees
        where fourth_accuracy is not null
        )a where count >0\\
        -- select @ColumnNames\\


    SET @sql := CONCAT('SELECT ', @ColumnNames, ' FROM compliance_employees');
    set @sql := REPLACE(@sql,'No_Result','"No Column have values" as No_Result')\\

     PREPARE stmt FROM @sql;
     EXECUTE stmt;          

在此处检查Live demo。

输出:

在此处输入图片说明

SELECT 
    first_accuracy, 
    second_accuracy
FROM
    compliance_employees CE
WHERE 
    first_accuracy IS NOT NULL
    AND second_accuracy IS NOT NULL

您是否要问如何从四个字段中选择值? 如果是这样,我建议使用GREATEST

SELECT 
    GREATEST(first_accuracy, second_accuracy) as accuracy
FROM
    compliance_employees CE;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM