英文:
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 | 
英文:
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`;
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论