Mysql查询:合并两个查询
下面是我正在使用的表的过度简化版本:
fruits +-------+---------+ | id | type | +-------+---------+ | 1 | apple | | 2 | orange | | 3 | banana | | 4 | apple | | 5 | apple | | 6 | apple | | 7 | orange | | 8 | apple | | 9 | apple | | 10 | banana | +-------+---------+
以下是两个感兴趣的查询:
SELECT * FROM fruits WHERE type='apple' LIMIT 2;
SELECT COUNT(*) AS total FROM fruits WHERE type='apple'; // output 6
我想组合这两个查询,以便结果如下所示:
+-------+---------+---------+ | id | type | total | +-------+---------+---------+ | 1 | apple | 6 | | 4 | apple | 6 | +-------+---------+---------+
输出必须限制为 2 条记录,但也应该包含 apple 类型的记录总数。
如何通过 1 个查询来完成此操作?
Below is an over-simplified version of table I'm using:
fruits +-------+---------+ | id | type | +-------+---------+ | 1 | apple | | 2 | orange | | 3 | banana | | 4 | apple | | 5 | apple | | 6 | apple | | 7 | orange | | 8 | apple | | 9 | apple | | 10 | banana | +-------+---------+
Following are the two queries of interest:
SELECT * FROM fruits WHERE type='apple' LIMIT 2;
SELECT COUNT(*) AS total FROM fruits WHERE type='apple'; // output 6
I want to combine these two queries so that the results looks like this:
+-------+---------+---------+ | id | type | total | +-------+---------+---------+ | 1 | apple | 6 | | 4 | apple | 6 | +-------+---------+---------+
The output has to be limited to 2 records but it should also contain the total number of records of the type apple.
How can this be done with 1 query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据MySQL如何解释它,它可能会缓存内部查询,这样它就不必为每条记录重新评估它。
另一种方法是使用嵌套查询和联接(例如,如果您需要多个水果类型,这将很有用):
Depending on how MySQL interprets it, it may cache the inner query so that it doesn't have to reevaluate it for every record.
Another way to do it is with a nested query and a join (this would be useful it you need more than one fruit type, for example):
为此,您应该使用
SQL_CALC_FOUND_ROWS
。将返回您的苹果的 ID,并记住如果没有 LIMIT 子句,它将返回多少个
苹果 将返回在没有 limit 语句的情况下会找到多少个苹果。
You should use
SQL_CALC_FOUND_ROWS
for that.will return the IDs of your apples, and remember how much it would have returned without the LIMIT clause
will return how many apples would have been found, without the limit statement.