V
V
Vladimir Golub2015-05-20 16:50:46
MySQL
Vladimir Golub, 2015-05-20 16:50:46

How to compare COUNT for equality with 0 in a query?

There is such a request

SELECT dialogs.id_dialog AS id, clients.name AS name, COUNT( messages.status) AS qt 
FROM dialogs INNER JOIN clients ON dialogs.id_client = clients.id_client INNER JOIN 
messages ON dialogs.id_dialog = messages.id_dialog WHERE dialogs.id_manager = '1' AND 
messages.status = '0' GROUP BY dialogs.id_dialog

How to put this in it
IF (COUNT( messages.status) == '0') COUNT( messages.status) = 0

That is, if the value of COUNT = 0, still display the record, but display 0 in the qt column.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Golub, 2015-05-20
@RazerVG

Here is the solution to my problem

SELECT dialogs.id_dialog AS id, clients.name AS name, SUM(case when messages.status = 0 then 1 else 0 end) AS qt 
FROM dialogs INNER JOIN clients ON dialogs.id_client = clients.id_client INNER JOIN 
messages ON dialogs.id_dialog = messages.id_dialog WHERE dialogs.id_manager = '1' GROUP BY dialogs.id_dialog

Now returns the number of messages with status 0.

H
He11ion, 2015-05-20
@He11ion

HAVING
as an example tftf.ru/stati/mysql/having or in google/ docs

G
George, 2015-05-20
@gogametreveli

SELECT dialogs.id_dialog AS id, clients.name AS name, SUM(IF(messages.status = '0',0,1)) AS qt 
FROM dialogs INNER JOIN clients ON dialogs.id_client = clients.id_client INNER JOIN 
messages ON dialogs.id_dialog = messages.id_dialog WHERE dialogs.id_manager = '1' AND 
messages.status = '0' GROUP BY dialogs.id_dialog

this is done via SUM(IF()), but you have a WHERE constraint messages.status = '0', so this query will always return qt =0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question