1
votes

Comment exécuter l'instruction SELECT en fonction des résultats d'autres colonnes?

J'ai une table MySQL comme celle-ci:

# something must be used to replace ???
SELECT (???) AS check, col1, col2 FROM my_table;

Et elle contient les données suivantes:

 entrez la description de l'image ici p>

Comment puis-je utiliser l'instruction SELECT pour générer un résultat comme celui-ci:

 entrez la description de l'image ici

La signification du contenu de la colonne check est la suivante:

`both` when both `col1` and `col2` have values.
`left` when only `col1` has a value.
`rightest` when only `col2` has a value.
`empty` when both `col1` and `col2` has empty value.

Je pense que la requête ressemblerait à quelque chose comme celle-ci p >

CREATE TABLE `my_table` (
  `col1` varchar(45) DEFAULT '',
  `col2` varchar(45) DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

??? doit être remplacé par autre chose.


2 commentaires

dev.mysql.com/doc/refman/5.7/en/case. html


Vous pouvez utiliser cas quand et changer le résultat dans chaque cas. Voici un exemple de stackoverflow.com/a/15745186/11005027


3 Réponses :


0
votes

Ci-dessous serait la requête -

select
col1, col2,
case 
when (nvl(col1) or col1='') and (nvl(col2) or col2='') then 'empty'
when (nvl(col1) or col1='') and (col2<>'') then 'right'
when (col1<>'') and (nvl(col2) or col2='') then 'left'
else 'Both' end as col3 from mytable


0 commentaires

0
votes

CASE WHEN pourrait faire ce que vous recherchez:

SELECT CASE WHEN col1 = '' 
            THEN CASE WHEN col2 = '' 
                      THEN 'empty'
                      ELSE 'right'
                 END
            ELSE CASE WHEN col2 = ''
                      THEN 'left'
                      ELSE 'both'
       END AS check,
       col1, col2 FROM my_table


0 commentaires

2
votes

Utilisez CASE WHEN Expression

SELECT CASE WHEN col1 = '' and col2='' then 'Empty'
            WHEN col1 = '' then 'Right'
            WHEN col2='' then 'Left'
            else 'Both' end as 'Check',
        col1, col2 FROM yourtablename


0 commentaires