简体   繁体   English

如何在mySQL中选择没有Null的最后一列

[英]How to select last column without Null in mySQL

I am facing an issue I cannot seem to find the solution of anywhere. 我面临的一个问题似乎无法找到任何解决方案。 I have a table in mySQL with following columns: 我在mySQL中有一个表,其中包含以下列:

RoleDuty1
RoleDuty2
RoleDuty3
RoleDuty4
RoleDuty5
RoleDuty6
RoleDuty7

This table has just one row or record. 该表只有一行或记录。 I want to see which is the last column in the table which is Not NULL ? 我想看看哪个是表中的最后一列是否为NULL meaning that I want to dynamically get Column Name RoleDuty7 as an answer from mySQL, since all of the columns have some value other than Null inside them. 这意味着我想动态获取列名 RoleDuty7作为mySQL的答案,因为所有列都有一些除Null之外的值。

Anyone has any idea how can I do this? 任何人都知道我该怎么做?

This is exactly what the coalesce function is for: 这正是coalesce函数的用途:

SELECT COALESCE(RoleDuty1,RoleDuty2,RoleDuty3,RoleDuty4,RoleDuty5,RoleDuty6,RoleDuty7,'All null) as FIRST_NON_NULL
FROM aTable

I think you have to use a COALESCE with a bunch of CASE statements, like this: 我认为你必须使用带有一堆CASE语句的COALESCE,如下所示:

SELECT COALESCE(rd1, rd2, rd3, rd4, rd5, rd6, rd7)
FROM
(SELECT
 CASE WHEN roleduty1 IS NOT NULL THEN 'roleduty1' ELSE NULL END AS rd1,
 CASE WHEN roleduty2 IS NOT NULL THEN 'roleduty2' ELSE NULL END AS rd2,
 ....
 FROM t) sub
SELECT (
    CASE FirstNullColumn
        WHEN 'RoleDuty1' THEN 'None'
        WHEN 'RoleDuty2' THEN 'RoleDuty1'
        WHEN 'RoleDuty3' THEN 'RoleDuty2'
        WHEN 'RoleDuty4' THEN 'RoleDuty3'
        WHEN 'RoleDuty5' THEN 'RoleDuty4'
        WHEN 'RoleDuty6' THEN 'RoleDuty5'
        WHEN 'RoleDuty7' THEN 'RoleDuty6'
        ELSE 'RoleDuty7'
        END
) AS LastNonNullColumn
FROM (
    SELECT (
        CASE
            WHEN RoleDuty1 IS NULL THEN 'RoleDuty1'
            WHEN RoleDuty2 IS NULL THEN 'RoleDuty2'
            WHEN RoleDuty3 IS NULL THEN 'RoleDuty3'
            WHEN RoleDuty4 IS NULL THEN 'RoleDuty4'
            WHEN RoleDuty5 IS NULL THEN 'RoleDuty5'
            WHEN RoleDuty6 IS NULL THEN 'RoleDuty6'
            WHEN RoleDuty7 IS NULL THEN 'RoleDuty7'
            ELSE 'None'
        END
    ) AS FirstNullColumn
    FROM MyTable
)

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

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