sql - 在 MySQL 的 SELECT 查询中使用 LIKE 进行 SWITCH

标签 sql mysql case switch-statement sql-like

我有这个标签表

CREATE TABLE IF NOT EXISTS `Tags` (
   `id_tag` int(10) unsigned NOT NULL auto_increment,
   `tag` varchar(255) default NULL,
   PRIMARY KEY  (`id_tag`),
   UNIQUE KEY `tag` (`tag`),
   KEY `id_tag` (`id_tag`),
   KEY `tag_2` (`tag`),
   KEY `tag_3` (`tag`),
   KEY `tag_4` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2937 ;

INSERT INTO `Tags` (`id_tag`, `tag`) VALUES
   (1816, '(class'),
   (2642, 'class\r\n\r\nâ?¬35'),
   (1906, 'class\r\nif'),
   (1398, 'class'),
   (2436, 'class)'),
   (1973, 'class:\n1.'),
   (2791, 'classes'),
   (1325, 'New'),
   (2185, 'pack'),
   (1905, 'packed'),
   (1389, 'WebClass');

我想获取标签与关键字 classpacknew 匹配的所有记录,以及指示这 3 个中哪一个的另一个字段关键字实际上与标签字段匹配。

以下查询没有给出正确的结果 查询 1

select id_tag,
case tag 
   when tag LIKE "%class%" then "class" 
   when tag LIKE "%new%" then "new"
   when tag LIKE "%pack%" then "pack"
end as matching_tag 
from Tags 
where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%"

我必须在箱子里使用类似的东西。否则完成匹配工作。以下查询有效:-

查询 2

select id_tag,
case tag 
   when "class" then "class" 
   when "new" then "new"
   when "pack" then "pack"
end as matching_tag 
from Tags 
where tag = "class" OR tag = "new" OR tag = "pack"

查询1有什么问题。请帮忙。

最佳答案

Mysql 支持两种大小写变体,您在查询 2 中使用的一种不太灵活,但仅支持单个变量的相等。另一个版本在 case 之后不指定变量,然后条件不必只是相等:

select id_tag,
case  
   when tag LIKE "%class%" then "class" 
   when tag LIKE "%new%" then "new"
   when tag LIKE "%pack%" then "pack"
end as matching_tag 
from Tags 
where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%"

documentation更多详情

编辑: 以下是关于为什么您的查询 #1 返回它返回的内容的更多解释:

case tag
   when tag LIKE "%class%" then "class" 
   when tag LIKE "%new%" then "new"
   when tag LIKE "%pack%" then "pack"
end as matching_tag

期望得到一个字面值,以便在 when ... then 之间进行比较 在上述情况下,表达式 tag LIKE "%class%"tag LIKE "%new%"tag LIKE "%pack%"都是在实际案例比较之前进行评估的。 但是(!),发生的情况是它们变为 0 或 1,并且与 tag 的值相比,它是 0 的第一个值,它将匹配任何 char(char 将被强制转换为 0) - 这与结果一致您的第一个查询。

这是一个显示相关表达式的逻辑值的查询:

select id_tag, tag LIKE "%class%", tag LIKE "%new%", tag = 0, case tag     when tag LIKE "%class%" then "class"     when tag LIKE "%new%" then "new"    when tag LIKE "%pack%" then "pack" end as matching_tag  from Tags  where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%";

这就是为什么你会得到意想不到的结果;沉默的 CAST 在这里是一个标准的陷阱。

关于sql - 在 MySQL 的 SELECT 查询中使用 LIKE 进行 SWITCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3082894/

相关文章:

php - 优化 MySQL 查询所需的建议

mysql - 计算mysql中表的行数

python - Python 3.+ 中另一个交替大小写的字符串

android - 我如何使用带微调器的开关?

php - 将音频文件长度保存在数据库中

java - native 查询错误

sql - 如何更改 MySQL 字段内的 URL?

sql - 有很多列的表

mysql - MySQL UPDATE ... JOIN ... CASE 的语法是否正确?

sql - 在 View 中执行存储过程?