Counting rows from a subquery

烂漫一生 提交于 2020-01-12 12:04:26

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5354273/counting-rows-from-a-subquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!