How could I show all values of MatchID that match in this WHERE CASE statement:
SELECT
`Word`,
CASE
WHEN `Word` LIKE 'a%' THEN 12
WHEN `Word`开发者_JAVA技巧 LIKE 'b%' THEN 13
WHEN `Word` LIKE 'a%' THEN 14
ELSE -1
END AS MatchID
FROM `Words`
My table contains a, b, and c, let's say. Right now, the results of this table are only showing:
a 12
b 13
I want it to also show:
a 14
In other words, I want the CASE clause to show all matches, not just the first match. Any ideas?
Thanks!
There's probably a more elegant way to do what you're asking, but here's one possible solution:
SELECT `Word`, 12 AS MatchID FROM `Words` WHERE `Word` like 'a%'
UNION
SELECT `Word`, 13 AS MatchID FROM `Words` WHERE `Word` like 'b%'
UNION
SELECT `Word`, 14 AS MatchID FROM `Words` WHERE `Word` like 'a%'
EDIT: If performance is a large concern then you could also consider a hybrid approach; use one SELECT with a CASE statement for a% and b%, and then UNION that with another SELECT for the second a%.
I think this should also work.
SELECT `Word`,
COALESCE(`MatchID`, -1) AS `MatchID`
FROM `Words`
LEFT JOIN (SELECT 'a%' AS `Match`, 12 AS `MatchID`
UNION ALL
SELECT 'b%' AS `Match`, 13 AS `MatchID`
UNION ALL
SELECT 'a%' AS `Match`, 14 AS `MatchID`) AS `Matches`
ON `Words`.`Word` LIKE `Matches`.`Match`
精彩评论