COUNT with conditions and selection without WHERE at the end

Asked

Viewed 101 times

1

In my table I have 3 columns:

  • id(INT) auto increment
  • tipo(INT): the values are 1 or 2
  • id_usuario(INT)

I need a means without the WHERE at the end to know if there is a user-specific data, and if there is a data from it, which displays the tipo(INT) if it is 1 or 2.

I can’t use the WHERE at the end because I’m doing a data count together. What I currently have:

SELECT 
COUNT(IF(tipo = 1, 1, NULL)) AS X, 
COUNT(IF(tipo = 2, 1, NULL)) AS W, 
COUNT() AS y, -->Conte se existe um dado do usuário especifico na tabela.
tipo AS Z     -->Mostrar dado do usuário especifico se é 1 ou 2.
FROM tabela WHERE id='$id'

1 answer

1


SELECT 
COUNT(IF(tipo = 1, 1, NULL)) AS X, 
COUNT(IF(tipo = 2, 1, NULL)) AS W, 
SUM(CASE WHEN id_user = '$id_user' AND tipo = '1' THEN 1 WHEN id_user = '$id_user' AND tipo = '2' THEN 2 ELSE 0 END) AS Y,
FROM curtidas WHERE id_post='$idPost'

After a few tests I arrived at this solution, and the best thing is that I gathered two things in one, If you have not given point 0, if it is different it shows whether the type is 1 or 2.

Browser other questions tagged

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