CASE in WHERE CLAUSE in MYSQL

跟風遠走 提交于 2019-12-02 02:29:23

You are on the right track with your second attempt, using logical AND/OR groupings instead of a CASE, but if you want to prefer the row matching cmp_brand over rows with an empty cmp_brand and expect only one result back, structure your ORDER BY to sort the non-empty cmp_brand first, and limit the overall result to 1.

SELECT thumb 
FROM inf_brand_images 
WHERE
  is_active=1 AND 
  ((cmp_brand = '' AND brand='NIKE') OR (cmp_brand='123_NIKE'))
/* non-empty cmp_brand will sort first */
ORDER BY cmp_brand <> '' DESC
/* and the end result is limited only to the first sorted row
   which will be the cmp_brand if matched, or the brand otherwise */
LIMIT 1

http://sqlfiddle.com/#!2/d176b/2

This works because the expression cmp_brand <> '' evaluates to the boolean true/false, which MySQL interprets as 1/0. A descending sort on those values forces the non-empty ones to sort fist (1 before 0).

Update after comments:

Since you do have the possibility of more than one row returned, you cannot rely on the ORDER BY. Instead, you can perform a LEFT JOIN against the same table. On one side, match cmp_brand = '' and on the other side match cmp_brand = '123_NIKE'. Importantly, return the thumb column from both sides of the join.

Wrap that in a subquery in the FROM clause, then at the top level you can use a SELECT CASE to prefer the cmp_brand if nonempty.

SELECT DISTINCT
  CASE WHEN cbcb IS NOT NULL THEN cbthumb ELSE bthumb END AS thumb
FROM (
  /* Return thumbs from both sides of the join */
  SELECT 
    b.thumb AS bthumb,
    b.cmp_brand AS bcb,
    cb.thumb AS cbthumb,
    cb.cmp_brand AS cbcb
  FROM
    inf_brand_images b
    /* join the table against itself with the matching cmp_brand in the join condition */
    LEFT JOIN inf_brand_images cb
      ON b.brand = cb.brand
      AND cb.cmp_brand = '123_NIKE'
  WHERE 
    /* The WHERE clause looks for empty cmp_brand on the left side of the join */
    b.brand = 'NIKE' AND b.cmp_brand = ''
) thumbs
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!