获取MySQL中非零列的索引。

huangapple go评论52阅读模式
英文:

how to get index of no zero column in mysql

问题

I have this table in my database.
我在我的数据库中有这张表。

I want to get the index of column which value equals 1 using select.
我想使用 select 来获取数值等于1的列的索引。

If there are many ones in one row, I want to get the first index.
如果一行中有多个1,我想获取第一个索引。

For example, 1 for the first row, 2 for the fifth row, 0 for the eighth row.
例如,第一行为1,第五行为2,第八行为0。

This is an SQL statement to initialize this table.
这是一个用于初始化这张表的SQL语句。

I want to get this result.
我想要获取这个结果。

result
L0
L1
L2
L3
L3
英文:

获取MySQL中非零列的索引。I have this table in my database.

I want to get the index of column which value equal 1 use select.
If have many one in one row,I want to get first index.
For example,1 for the first row,2 for the fifth row,0 for the eighth row.
this is a sql for init this table.

CREATE TABLE `action` (
  `action_id` BIGINT NOT NULL AUTO_INCREMENT,
  `action_level_0` SMALLINT DEFAULT NULL COMMENT 'L0',
  `action_level_1` SMALLINT DEFAULT NULL COMMENT 'L1',
  `action_level_2` SMALLINT DEFAULT NULL COMMENT 'L2',
  `action_level_3` SMALLINT DEFAULT NULL COMMENT 'L3',
   PRIMARY KEY (`action_id`)
) ENGINE=INNODB AUTO_INCREMENT=2
INSERT INTO `action` 
(`action_level_0`,`action_level_1`,`action_level_2`,`action_level_3`)
VALUES
(1,0,0,0),
(0,1,0,0),
(0,0,1,0),
(0,0,0,1),
(0,0,0,1);

I want to get this reuslt

result
L0
L1
L2
L3
L3

答案1

得分: 1

你可以使用 CASE WHEN 子句来实现:

select case when action_level_0 = 1 then 'L0'
            when action_level_1 = 1 then 'L1'
            when action_level_2 = 1 then 'L2'
            when action_level_3 = 1 then 'L3' end as Result
from `action`;

演示在这里

英文:

You can do it using CASE WHEN clause :

select case when action_level_0 = 1 then 'L0'
            when action_level_1 = 1 then 'L1'
            when action_level_2 = 1 then 'L2'
            when action_level_3 = 1 then 'L3' end as Result
from `action`;

Demo here

答案2

得分: 1

以下是翻译好的部分:

"不对表进行标准化的一种方法是执行以下操作:"

select 
  case when `action_level_0` = 1 then 'L0'
       when `action_level_1` = 1 then 'L1'
       when `action_level_2` = 1 then 'L2'
       when `action_level_3` = 1 then 'L3'
       else 'N/A' end as result
from `action`

参见fiddle http://sqlfiddle.com/#!9/baa2f/10,但正如指出的那样,创建列可能是明智之举。

英文:

One way without normalising the table is to do something like

select 
  case when `action_level_0` = 1 then 'L0'
       when `action_level_1` = 1 then 'L1'
       when `action_level_2` = 1 then 'L2'
       when `action_level_3` = 1 then 'L3'
       else 'N/A' end as result
from `action`

See fiddle http://sqlfiddle.com/#!9/baa2f/10 but as pointed out it may be wise to create column as pointed out.

huangapple
  • 本文由 发表于 2023年4月13日 16:38:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定