I want to show the count in the SQL query, but I have a problem with it. I want to search for count only if there is something specific in the value column. Here is an example of my query:
SELECT COUNT(IF status='F') FROM relation WHERE from='7'
So, here I want to get the amount of "relation" from the column "status" from the table, when the status value is F.
With the above code, I get an error message:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`status`='F') FROM `relation` WHERE `from`='7' LIMIT 0, 25' at line 1
3
Answers
You can count this way to get only counts where the value of
status
is FI think two common ways are:
and
The first one uses
count
but since it only counts non-null values, it only counts the ones you want. The second usessum
, but since we sum 1 if your condition is true and 0 if your condition is false it’s equivalent to counting where the condition is true.Although in your case since you’re not doing a
group by
you could just useI prefer summing a boolean expression:
Note that
FROM
is a reserved MySQL keyword. If you really did name a columnFROM
, then you will have to forever escape it in backticks. You should avoid naming your database objects using reserved keywords.