Conditional in Mysql clause

Asked

Viewed 135 times

-3

I have a select normal

SELECT campos FROM tabela_Z WHERE condicoes

I’d like that one query add a field that is another query.

SELECT 
   campo1,
   campo2,
   campo3,
   (SE houver o id X na TABELA _, = true, caso contrario = false) 
FROM tabela_Z
WHERE condicoes

How to do this?

It would be something like that I need:

SELECT  
   membros.idMembro,
   membros.nome,
   membros.apelido,
   membros.bloqueado,
   membros.usuario,
   membros.senha,
   acessos.idAcesso,
   acessos.nome
   (SELECT IF(admins.idMembro=1, 's', 'n') FROM admins)
FROM membros , acessos, acessosmembros
WHERE 
   membros.usuario ='caca' AND 
   membros.senha ='aaaa' AND
   acessosmembros.idMembro = membros.idMembro AND
   acessosmembros.idAcesso = acessos.idAcesso

If I do

SELECT IF(admins.idMembro=1, 's', 'n') FROM admins

In the phpmyadmin, have correct return.

But I need to insert it into one of the selects of query

  • This guy id X is in the same table? If there is more than one result in the query, all will return the same true or false since in the consultation will be passed only one id X, right?

  • search by Mysql IF() Function example https://www.w3schools.com/sql/func_mysql_if.asp see also https://www.w3resource.com/mysql/control-flow-functions/if-function.php

  • this id x is not in the same table. It’s kind of to add a field to the Array that will be populated by the result of this query

  • I added details to the question!

  • It worked, missing a comma at the end of hits.

1 answer

0

As you said in comment, missing a comma after the penultimate field of select. To make the consultation more dynamic, I changed the validation condition, checking if the id of subquery is the same as the main (admins.idMembro=acessosmembros); thus, it will have the correct value for each returned user (without needing to modify the query for each query).

SELECT  
   membros.idMembro,
   membros.nome,
   membros.apelido,
   membros.bloqueado,
   membros.usuario,
   membros.senha,
   acessos.idAcesso,
   acessos.nome,
   (SELECT IF(admins.idMembro=acessosmembros,idMembro, 's', 'n') FROM admins)
FROM membros, acessos, acessosmembros
WHERE 
   membros.usuario ='caca' AND 
   membros.senha ='aaaa' AND
   acessosmembros.idMembro = membros.idMembro AND
   acessosmembros.idAcesso = acessos.idAcesso

Browser other questions tagged

You are not signed in. Login or sign up in order to post.