我希望我的查询显示获得的结果总数。
例如,如果我执行此查询:
SELECT user, email FROM users WHERE user = 'Daniel';
显示第三列以及总行数。使用user = 'Daniel'
,我总共有13条记录,这就是我要显示的记录:
user email total
-------------------------------------------------
Daniel email1@gmail.com 13
Daniel email2@gmail.com 13
Daniel email3@gmail.com 13
Daniel email4@gmail.com 13
....
可以这样做吗?
答案 0 :(得分:0)
尝试如下
SELECT u2.user, u2.email,
(select count(*) from users u1 where u1.user=u2.user ) as total
FROM users u2
WHERE u2.user = 'Daniel';
如果mysql版本> = 8.0,则可以使用count()窗口函数
select user,email,count(*) over() as total
from users
WHERE user = 'Daniel'
答案 1 :(得分:0)
我更喜欢在这里使用解析函数:
SELECT
user,
email,
COUNT(*) OVER () total
FROM users
WHERE user = 'Daniel';
如果由于使用的是MySQL的早期版本而无法使用解析函数,请使用联接:
SELECT
u1.user,
u1.email,
u2.cnt AS total
FROM users u1
INNER JOIN
(
SELECT user, COUNT(*) AS cnt
FROM users
-- we could also restrict to Daniel here, but I am showing a general
-- solution for multiple users
GROUP BY user
) u2
ON u1.user = u2.user
WHERE
u1.user = 'Daniel';
答案 2 :(得分:0)
我不明白为什么您需要为组中的所有行重复相同的计数。不过,以下查询会执行您想要的相同操作
Select user, email, count(distinct *)
over
() as total from table ;