在MySql中选择任一列或三列中的特定列

时间:2018-02-14 04:51:55

标签: mysql mysql-workbench

我有一个像这样的表值

     A        |       B     |      C      |
+-------------+-------------+-------------+
|          10 |           6 |           1 |
|           8 |          10 |          11 |
|           5 |           8 |          10 |
|          10 |           8 |             |
|           4 |          10 |           6 |

现在我需要在列中选择值为10的列名称

预期结果

| Result      |
+-------------+
|          A  |
|          B  |
|          C  |
|          A  |
|          B  |
+-------------+

我已尝试过此查询

选择A = 10时的情况,然后A else B从表中结束;

如果比较C错误来自任何解决方案

只能比较两列

2 个答案:

答案 0 :(得分:1)

select case when A=10 then 'A' 
                when B=10 then 'B'
                when C=10 then 'C'  
                    end  from mytable;

答案 1 :(得分:1)

CREATE TABLE `testtable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `A` int(11) DEFAULT NULL,
  `B` int(11) DEFAULT NULL,
  `C` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4

INSERT INTO `testtable` (`id`,`A`,`B`,`C`) VALUES (1,10,6,1);
INSERT INTO `testtable` (`id`,`A`,`B`,`C`) VALUES (2,8,10,11);
INSERT INTO `testtable` (`id`,`A`,`B`,`C`) VALUES (3,5,8,10);
INSERT INTO `testtable` (`id`,`A`,`B`,`C`) VALUES (4,10,8,NULL);
INSERT INTO `testtable` (`id`,`A`,`B`,`C`) VALUES (5,4,10,6);

SELECT CASE WHEN A=10 THEN A END AS resulta,CASE WHEN B=10 THEN B END AS resultb,CASE WHEN C=10 THEN C END AS resultc FROM testtable;

SELECT CASE WHEN A=10 THEN A ELSE (SELECT CASE WHEN B=10 THEN B ELSE (SELECT CASE WHEN C=10 THEN C END AS resultc)END AS resultb) END AS resulta FROM testtable;

SELECT CASE WHEN A=10 THEN 'A' ELSE (SELECT CASE WHEN B=10 THEN 'B' ELSE (SELECT CASE WHEN C=10 THEN 'C' END AS resultc)END AS resultb) END AS resulta FROM testtable;