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
- Here is an example where 123_NIKE matches: http://sqlfiddle.com/#!2/dfe228/31
- And an example where 124_NIKE does not match: http://sqlfiddle.com/#!2/dfe228/32