Mysql
 sql >> Base de données >  >> RDS >> Mysql

CASE dans WHERE CLAUSE dans MYSQL

Vous êtes sur la bonne voie avec votre deuxième tentative, en utilisant la logique AND/OR regroupements au lieu d'un CASE , mais si vous voulez préférer la ligne correspondant à cmp_brand sur les lignes avec un cmp_brand vide et attendez un seul résultat, structurez votre ORDER BY pour trier les cmp_brand non vides en premier, et limiter le résultat global à 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

Cela fonctionne car l'expression cmp_brand <> '' évalue au booléen true/false , que MySQL interprète comme 1/0 . Un tri décroissant sur ces valeurs oblige celles qui ne sont pas vides à trier en premier (1 avant 0).

Mise à jour après commentaires :

Puisque vous avez la possibilité de renvoyer plus d'une ligne, vous ne pouvez pas compter sur le ORDER BY . Au lieu de cela, vous pouvez effectuer un LEFT JOIN contre la même table. D'un côté, faites correspondre cmp_brand = '' et de l'autre côté correspond cmp_brand = '123_NIKE' . Surtout, retournez le thumb colonne de les deux côtés de la jointure.

Enveloppez cela dans une sous-requête dans le FROM clause, puis au niveau supérieur, vous pouvez utiliser un SELECT CASE préférer le cmp_brand si non vide.

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