Sei sulla strada giusta con il tuo secondo tentativo, usando raggruppamenti logici AND/OR invece di un CASE, ma se vuoi preferire la riga che corrisponde a cmp_brand rispetto alle righe con cmp_brand vuoto e ti aspetti di ricevere indietro un solo risultato, struttura il tuo ORDER BY in modo da ordinare per primi i cmp_brand non vuoti e limita il risultato complessivo a 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 https://sqlfiddle.com/#!2/d176b/2
Questo funziona perché l'espressione cmp_brand <> '' si valuta come il booleano true/false, che MySQL interpreta come 1/0. Un ordinamento decrescente su quei valori forza i non vuoti a ordinarsi per primi (1 prima di 0).
Aggiornamento dopo i commenti:
Poiché esiste la possibilità di ricevere più di una riga, non puoi fare affidamento sull'ORDER BY. Puoi invece eseguire una LEFT JOIN verso la stessa tabella. Da un lato, abbina cmp_brand = '' e dall'altro cmp_brand = '123_NIKE'. Importante: restituisci la colonna thumb da entrambi i lati del join.
Racchiudi il tutto in una sottocquery nella clausola FROM, poi al livello superiore puoi usare una SELECT CASE per preferire il cmp_brand se non è vuoto.
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 - Qui c'è un esempio dove 123_NIKE corrisponde: https://sqlfiddle.com/#!2/dfe228/31
- E un esempio dove 124_NIKE non corrisponde: https://sqlfiddle.com/#!2/dfe228/32