Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting rows from a subquery

How could I count rows from a SELECT query as a value? Such as

SELECT FUCNTIONIMLOOKINGFOR(SELECT * FROM anothertable) AS count FROM table;

So that count is an integer of how many rows the subquery SELECT * FROM anothertable returns.

EDIT

SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
    (
        SELECT COUNT(f.FlagTime)
            FROM Flags as f 
                JOIN Posts as p 
                ON p.PostPID = f.FlagPID
    ) as PostFlags
    FROM Posts AS p
        JOIN Users AS u
        ON p.PostUID = u.UserUID
    ORDER BY PostTime DESC
    LIMIT 0, 30
like image 778
Shoe Avatar asked Mar 18 '11 15:03

Shoe


People also ask

How do I count rows in SQL subquery?

SELECT FUCNTIONIMLOOKINGFOR(SELECT * FROM anothertable) AS count FROM table; So that count is an integer of how many rows the subquery SELECT * FROM anothertable returns.

How do I count results in SQL query?

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 count be used in WHERE clause?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause.

Can we use subquery in SUM function?

A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM, COUNT, MIN, or MAX function, but you do not want the aggregate function to apply to the main query.


2 Answers

SELECT ( SELECT COUNT(id) FROM aTable ) as count FROM table

I assume your example is a truncated version of your actual query, so perhaps you should post what you are after to get a, possibly, more optimal query.

EDIT

Working directly from my brain, something like this should be more optimal.

SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep, COUNT(v.FlagTime) as postFlags
    FROM Flags as f 
    JOIN Posts as p ON p.PostPID = f.FlagPID
    JOIN Users AS u ON p.PostUID = u.UserUID
LIMIT 0, 30
GROUP BY p.PostPID
ORDER BY PostTime DESC
like image 114
Kevin Peno Avatar answered Oct 12 '22 11:10

Kevin Peno


You can say

SELECT COUNT(*) FROM anothertable

which will return a numeric value, which you can use in another query, such as in the select list of another query, or as a condition in another query.

SELECT someVariable FROM table
WHERE (SELECT COUNT(*) FROM anotherTable) > 5

OR

SELECT someVariable, (SELECT COUNT(*) FROM anotherTable) as count FROM table
like image 31
Brett Avatar answered Oct 12 '22 09:10

Brett