Martin AJ Martin AJ - 2 months ago 10
MySQL Question

How can I count selected rows in MySQL?

Here is my query:

SELECT
a.*
FROM
qanda q
JOIN
qanda a ON q.Id = a.related
WHERE
a.type = 1
AND a.author_id = 29
AND q.amount IS NULL;


Now, it selects 3 rows in reality. Ok I want it returns
3
instead of
a.*
. Actually I don't need any valye of those columns, I just need to count the number of selected rows. How can I do that?

Note: I can use my current query and then count the number of rows by PHP. But I don't like that.

Answer

Simple. Use COUNT() in MySQL

SELECT 
    COUNT(a.id) as count
FROM
    qanda q
        JOIN
    qanda a ON q.Id = a.related
WHERE
    a.type = 1
AND a.author_id = 29
AND q.amount IS NULL;
Comments