mysql计算行数据,计算MySQL中的行以及实际行内容

Is there a way in MySQL to do a single SQL statement that returns the selected rows along with the count of the result rows?

I can do this:

SELECT COUNT(*) FROM BigTable WHERE firstname LIKE 'a%';

Which gives me a single result row with the count (37,781). I can get the actual row data like this:

SELECT firstname FROM BigTable WHERE firstname LIKE 'a%';

which displays the actual 37,781 rows. But when I try to combine them, like this:

SELECT firstname, COUNT(*) FROM BigTable WHERE firstname LIKE 'a%';

I get a single row with the first row that matches the query, and the total count of records that matches the query.

What I'd like to see is two columns with 37,781 rows. The first column should contain the first name for each row and the second column should contain the number '37,781' for every row. Is there a way to write the query to accomplish this?

解决方案

You can use a CROSS JOIN. The subquery will get the count for all firstnames and then it will include this value in each row:

SELECT firstname, d.total

FROM BigTable

CROSS JOIN

(

SELECT COUNT(*) total

FROM BigTable

WHERE firstname LIKE 'a%'

) d

WHERE firstname LIKE 'a%';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值