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

时间:2016-12-02 20:36:34

标签: mysql sql database

我面临的一个问题似乎无法找到解决方案。我在mySQL中有一个表,其中包含以下列:

RoleDuty1
RoleDuty2
RoleDuty3
RoleDuty4
RoleDuty5
RoleDuty6
RoleDuty7

此表只有一行或记录。我想看看哪个是表中的最后一列 Not NULL 意味着我想动态获取列名 {{1作为mySQL的答案,因为所有列都有一些除Null之外的值。

任何人都知道我该怎么做?

3 个答案:

答案 0 :(得分:1)

这正是合并功能的用途:

struct

答案 1 :(得分:0)

我认为你必须使用带有一堆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

答案 2 :(得分:0)

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
)