比较字符串中的单词与单元格

时间:2014-07-14 09:41:30

标签: mysql

鉴于以下内容:

create table original (
dbString VARCHAR(255),
c_Alfa TINYINT(4) Default 0,
c_Bravo TINYINT(4) default 0,
c_Charlie  TINYINT(4) default 0
);

INSERT INTO original (dbString) VALUES
('Charlie Echo Delta',0,0,0),
('Foxtrot Golf Hotel',0,0,0),
('Alfa Oscar Tango',0,0,0),
('Charlie Bravo India',0,0,0);

SET @c_string := 'Alfa Bravo Charlie';

是否可以在mysql中将@c_string中的单词(单词为:Alfa,Bravo和Charlie)与表原始中的 dbString 列进行比较并检查如果单元格中出现一个或多个单词。

结果应该是

+---------------------+------------+------------+------------+
| dbString            | c_Alfa     | c_Bravo    | c_Charlie  |
+---------------------+------------+------------+------------+
| Charlie Echo Delta  | 0          | 0          | 1          |
| Foxtrot Golf Hotel  | 0          | 0          | 0          |
| Alfa Oscar Tango    | 1          | 0          | 0          |
| Charlie Bravo India | 0          | 1          | 1          |
+---------------------+------------+------------+------------+

我还创造了一个小提琴:http://sqlfiddle.com/#!2/8eb2b/1

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT dbString,
       IF(locate('Alfa',dbString), 1, 0) AS c_Alfa,
       IF(locate('Bravo',dbString), 1, 0) AS c_Bravo,
       IF(locate('Charlie',dbString), 1, 0) AS c_Charlie
FROM original;

检查SQL Fiddle

答案 1 :(得分:0)

我认为你应该在任何条件下使用LIKE,例如:
查询:

SELECT * FROM original WHERE dbString LIKE ("%" + @c_string + "%");