Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select count and other records in one single query

Tags:

I have the following query

select main_cat_name,cat_url from mf_main order by main_cat_name 

This returns whole data of my table.Now i want to have count of the total rows of this table.I can do it using another query but how can i use them in one single query???

I want two data ONE :- the rows of the table TWO:- the count how can i have that in one single query

I tried this but it gives correct count but displays only first row of the table :

select count(cat_id),main_cat_name,cat_url from mf_main order by main_cat_name 
like image 460
developer Avatar asked Dec 09 '09 07:12

developer


People also ask

How do I use select and count together in SQL?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can we use count in select query?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).


2 Answers

You can try with Group By like:

SELECT count(cat_id), main_cat_name, cat_url FROM mf_main GROUP BY main_cat_name, cat_url ORDER BY main_cat_name 

Right solution i hope:

This is what you want:)

SELECT x.countt, main_cat_name, cat_url FROM mf_main, (select count(*) as countt FROM mf_main) as x ORDER BY main_cat_name 

If you use mysql u have "as" like i did. For others db may be without as (like oracle)

like image 132
Cristian Boariu Avatar answered Oct 08 '22 14:10

Cristian Boariu


You could try

select main_cat_name,cat_url, COUNT(*) OVER () AS total_count from mf_main order by main_cat_name 

Not sure if MySQL accepts the AS, just remove it if it does not.

like image 30
Peter Lang Avatar answered Oct 08 '22 16:10

Peter Lang