简体   繁体   English

COUNT行SQL查询涉及SELECT特定行+ FROM + WHERE + AND

[英]COUNT rows of sql query involving SELECT specific rows+FROM+WHERE+AND

How do I return the count of rows returned by this query instead of query results: 如何返回此查询返回的行数而不是查询结果:

SELECT collections.name, collections.description, collections.collection_id, collections.name, collections.description, collections.date, users.name
FROM users, collections
WHERE collections.user_id = users.user_id
AND (
collections.description LIKE  "%%searchTerm%%"
OR collections.name LIKE  "%%searchTerm%%"
OR users.name LIKE  "%%searchTerm%%"
)
AND (
reported = false
OR (
reviewed = true
AND approved = true
)
)

Two ways, you could 两种方式,您可以

SELECT count(*)
FROM...

which will return the count at the expense of the actual data, or you can use a function in whichever language you're using to query the database to check how many rows there are. 这将以实际数据为代价返回计数,或者您可以使用用于查询数据库以检查有多少行的任何语言的函数。

You can do use count(1) or count(collections.collection_id) 您可以使用count(1)或count(collections.collection_id)

SELECT 
    count(collections.collection_id)
FROM 
    users,
    collections
WHERE 
    collections.user_id = users.user_id
    AND (
            collections.description LIKE  "%%searchTerm%%"
            OR collections.name LIKE  "%%searchTerm%%"
            OR users.name LIKE  "%%searchTerm%%"
        )
    AND (
        reported = false
        OR (
            reviewed = true
            AND approved = true
        )
    )

See also FOUND_ROWS() along with SQL_CALC_FOUND_ROWS http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows 另请参阅FOUND_ROWS()和SQL_CALC_FOUND_ROWS http://dev.mysql.com/doc/refman/5.0/zh-CN/information-functions.html#function_found-rows

It might perform better than doing one query with a COUNT(*) and another to get the data. 它可能比使用COUNT(*)执行一个查询和执行另一个查询来获取数据要好。

ie can run one query to get the results - and at the same time get a count. 即可以运行一个查询来获取结果-同时获得一个计数。 (ok, you do still use two queries, but the second is cheap, its just fetching the calculated total) (好的,您仍然使用两个查询,但是第二个查询很便宜,它只是获取计算出的总数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM