仅当其值为1时才如何串联一系列类型为(1)的字段?

时间:2018-10-08 03:55:56

标签: mysql

requests表中包含一系列与请求中的一系列可能要求相对应的bit(1)类型字段

CREATE TABLE requests (
  `id` int,
  `classroom` varchar(255),
  `speaker` bit(1),
  `datashow` bit(1),
  `wifi` bit(1),
  `pointer` bit(1)
);

当值为1时,是否可以连接扬声器,数据显示,wifi和指针字段?

因此具有以下数据集

insert into requests
  (`id`, `classroom`, `speaker`, `datashow`, `wifi`, `pointer`)
values
  (1, 'A101', true, false, false, false),
  (2, 'A102', true, true, false, false),
  (3, 'A103', true, false, true, false),
  (4, 'A104', false, false, false, false),
  (5, 'A101', false, false, false, true)

是否有可能获得与以下类似的结果?

+----+-----------+--------------------+
| id | classroom | requirements       |
+----+-----------+--------------------+
|  1 | A101      | speaker            |
|  2 | A102      | speaker datashow   |
|  3 | A103      | speaker wifi       |
|  4 | A104      |                    |
|  5 | A101      | pointer            |
+----+-----------+--------------------+

此刻,我正在尝试concat的一系列case when,但没有成功

select
  id,
  classroom,
  concat (
    (case when speaker = 1 then 'speaker ' end),
    (case when datashow = 1 then 'datashow ' end),
    (case when wifi = 1 then 'wifi ' end),
    (case when pointer = 1 then 'pointer' end)
  ) requirements
from
  requests

我添加了此sqlfiddle以促进您的协作

预先感谢

2 个答案:

答案 0 :(得分:1)

尝试

select
  id,
  classroom,
  concat (
    (case when speaker = 1 then 'speaker ' else '' end),
    (case when datashow = 1 then 'datashow ' else '' end),
    (case when wifi = 1 then 'wifi ' else '' end),
    (case when pointer = 1 then 'pointer' else '' end)
  ) requirements
from
  requests

您的案例返回null,并与null连接也返回null

答案 1 :(得分:1)

在此处尝试使用CONCAT_WS。此函数将忽略NULL个组件,并且只会在两个条目之间使用空格分隔符,而不会在结尾处使用

SELECT
    id,
    classroom,
    CONCAT_WS(' ', CASE WHEN speaker THEN 'speaker' END,
              CASE WHEN datashow THEN 'datashow' END,
              CASE WHEN wifi     THEN 'wifi' END,
              CASE WHEN pointer  THEN 'pointer' END) AS requirements
FROM requests
ORDER BY id;

enter image description here

Demo