开发者

Allow duplicate matches for a CASE statement

开发者 https://www.devze.com 2023-03-24 18:46 出处:网络
How could I show all values of MatchID that match in this WHERE CASE statement: SELECT `Word`, CASE WHEN `Word` LIKE \'a%\' THEN 12

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`  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号