MySQL 计算子查询中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5354273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting rows from a subquery
提问by Shoe
How could I count rows from a SELECT query as a value? Such as
如何将 SELECT 查询中的行计算为值?如
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.
因此该计数是子查询SELECT * FROM anothertable
返回的行数的整数。
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
回答by Kevin Peno
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
回答by Brett
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