3

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.

4
  • 1
    The answer below is probably your best solution. Your driver also should have a function for this, php.net/manual/en/pdostatement.rowcount.php, php.net/manual/en/mysqli-result.num-rows.php Commented Sep 9, 2016 at 1:05
  • @chris85 Even if the driver supports it, you still have to have MySQL query and count the number of rows. Commented Sep 9, 2016 at 1:10
  • @Pachonk ...yea that's why the comment was prefaced with The answer below is probably your best solution. Commented Sep 9, 2016 at 1:12
  • Completely understood, I just wanted to make it clear that even though it's option is available, it would be less efficient. I didn't mean to come off mean. Commented Sep 9, 2016 at 1:13

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Just one thing, Why not COUNT(1) instead of COUNT(a.id) ?
No reason. Personal preference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.