MySQL-varchars的多种情况

时间:2018-11-13 10:46:15

标签: mysql

我正在尝试使用CASE WHEN来计算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");

2 个答案:

答案 0 :(得分:1)

似乎您需要检查字段中是否同时没有单词foundmissing,然后将值设置为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 |

答案 1 :(得分:0)

您的查询有冲突

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循环时,这是不可接受的。