varchars的多个case

owfi6suc  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(229)

我试图使用case来计算特定文本何时包含varchar列。我一直试图破解它,但我有一个问题时,第二,第三种情况时,被添加。我使用的代码是:

SELECT *,
    CASE 
    WHEN (Orders.Some_text LIKE "%test%" AND Orders.Some_text NOT LIKE "%found%") THEN 1

    ELSE 0 END AS Test
    FROM Orders;

现在我添加第二种情况:

SELECT *,
    CASE 
    WHEN (Orders.Some_text LIKE "%test%" AND Orders.Some_text NOT LIKE "%found%") THEN 1
    WHEN (Orders.Some_text LIKE "%test%" AND Orders.Some_text NOT LIKE "%missing%") THEN 1
    ELSE 0 END AS Test
    FROM Orders;

它在测试列中产生错误。
当单词测试被发现时,我想要的结果只是简单的1,并且它没有被发现、丢失或/和在测试过程中。

+------+--------------+------------+
| id   | Some_text          | Test |
+------+--------------+------------+
|    1 | test               |    1 |
|    2 | test found         |    0 |
|    3 | found test         |    0 |
|    4 | test missing       |    0 |
|    5 | missing test       |    0 |
|    6 | test during        |    0 |
|    7 | during test found  |    0 |
|    8 | abc                |    0 |
+------+--------------+------------+

复制数据集的代码:

CREATE TABLE Orders
(

id INT,
Some_text char(255));

insert into Orders values (1,   "test");
insert into Orders values (2,   "test found");
insert into Orders values (3,   "found test");
insert into Orders values (4,   "test missing");
insert into Orders values (5,   "miss   ing test");
insert into Orders values (6,   "test during");
insert into Orders values (7,   "during test found");
insert into Orders values (8,   "abc");
toe95027

toe950271#

看来你得检查一下这两个词 found 以及 missing 如果字段中没有,则将值设置为1。
组合如下语句,它应该返回预期的输出。

SELECT *,
CASE 
WHEN (Orders.Some_text LIKE "%test%" AND
      Orders.Some_text NOT LIKE "%found%" AND
      Orders.Some_text NOT LIKE "%missing%") THEN 1
ELSE 0 END AS Test
FROM Orders;

输出

+------+--------------+------------+
| id   | Some_text          | Test |
+------+--------------+------------+
|    1 | test               |    1 |
|    2 | test found         |    0 |
|    3 | found test         |    0 |
|    4 | test missing       |    0 |
|    5 | missing test       |    0 |
|    6 | test during        |    1 |
|    7 | during test found  |    0 |
|    8 | abc                |    0 |
cidc1ykv

cidc1ykv2#

你的查询有冲突,

WHEN (Orders.Some_text LIKE "%test%" AND Orders.Some_text NOT LIKE "%found%")

WHEN (Orders.Some_text LIKE "%test%" AND Orders.Some_text NOT LIKE "%missing%")

两者可能包含相同的结果。这在使用case循环时是不可接受的。

相关问题