[Solved] Echoing a pseudo column value after a COUNT
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Echoing a pseudo column value after a COUNT

Database type:

Please don't beat me if this is elementary. I searched and found disjointed stuff relating to pseudo columns. Nothing spot on about what I need.

Anyway... I have a table with some rows. Each record has a unique ID, an ID that relates to another entity and finally a comment that relates to that last entity.

So, I want to COUNT these rows to basically find what entity has the most comments.

Instead of me explaining the query, I'll print it

SELECT entity_id, COUNT(*) AS amount FROM comments GROUP BY entity_id ORDER BY amount DESC

The query does just what I want, but I want to echo the values from that pseudo column, 'amount'

Can it be done, or should I use another method like mysql_num_rows?

Thank you!!!

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `comments` ADD INDEX `comments_idx_entity_id` (`entity_id`);
The optimized query:
        COUNT(*) AS amount 
        amount DESC

Related Articles

* original question posted on StackOverflow here.