从子查询计数行

时间:2011-03-18 15:33:43

标签: mysql sql subquery

我如何将SELECT查询中的行计为值? 如

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

因此count是子查询SELECT * FROM anothertable返回的行数的整数。

修改

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

2 个答案:

答案 0 :(得分:19)

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

我认为你的例子是你的实际查询的截断版本,所以也许你应该发布你想要的,可能是更优化的查询。

修改

直接从我的大脑工作,这样的事情应该更加优化。

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

答案 1 :(得分:7)

你可以说

SELECT COUNT(*) FROM anothertable

将返回一个数值,您可以在另一个查询中使用该值,例如在另一个查询的选择列表中,或作为另一个查询中的条件。

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

OR

SELECT someVariable, (SELECT COUNT(*) FROM anotherTable) as count FROM table