San*_*ath 27 mysql sql 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');
Run Code Online (Sandbox Code Playgroud)
我想取其中标签匹配关键字的所有记录class
或pack
或new
与这表明该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%"
Run Code Online (Sandbox Code Playgroud)
我必须在案例中使用类似的东西.否则完全匹配工作.以下查询有效: -
查询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"
Run Code Online (Sandbox Code Playgroud)
查询有什么问题1.请帮忙.
Unr*_*son 38
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%"
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅文档
编辑:这里有一个更多的解释为什么你的查询#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
Run Code Online (Sandbox Code Playgroud)
期望获得用于比较的文字值.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%";
Run Code Online (Sandbox Code Playgroud)
这就是你得到意想不到的结果的原因; 沉默的CAST是一个标准的陷阱.
Vla*_*pak 13
只是想提醒一下,关于else子句:
case
when tag LIKE "%class%" then "class"
when tag LIKE "%new%" then "new"
when tag LIKE "%pack%" then "pack"
else "no one"
end as matching_tag
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
60017 次 |
最近记录: |