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 |
2
Answers
You can do it using
CASE WHEN
clause :Demo here
One way without normalising the table is to do something like
See fiddle http://sqlfiddle.com/#!9/baa2f/10 but as pointed out it may be wise to create column as pointed out.