Mysql supports two variants of case, the one you use in query 2 is less flexible but supports only equality on a single variable. The other version specifies no variable after case and then conditions need not be only equality:
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%"
See documentation for further details
EDIT:
Here’s a bit more explanation on why your query #1 returned what it returned:
case tag
when tag LIKE "%class%" then "class"
when tag LIKE "%new%" then "new"
when tag LIKE "%pack%" then "pack"
end as matching_tag
expects to get a literal value for comparison between when ... then
In the above case the expressions tag LIKE "%class%"
, tag LIKE "%new%"
and tag LIKE "%pack%"
are all evaluated before the actual case comparison.
However (!), what happens is that they become either 0 or 1 and when compared to the value of tag it is the first value of 0 that will match any char (char will get cast to 0) – this is consistent with the results of your first query.
Here’s a query that shows the logical values for the relevant expressions:
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%";
That’s why you get unexpected results; the silent CAST is a standard pitfall here.