以下是用于从数据库中提取数据的当前代码
$query = "SELECT username,time,UNIX_TIMESTAMP(time) as timestamp,UNIX_TIMESTAMP(active) as activestamp,IP FROM ".$table_name." WHERE success='1' ORDER BY active DESC";
以下是一组示例数据(删除了所有不重要的字段)
ID | username
_01 | admin
_02 | admin
_03 | bob
_04 | jill
我想要的是每个用户出现的总次数,例如:
admin (2)
bob (1)
jill (1)
我需要将这个COUNT(IF(name = 'admin', 1, NULL)) AS login_totals
的内容添加到我向您展示的原始查询中,但我无法弄清楚正确的代码。我的示例中的admin名称必须是当前的用户名,所以我只是将“用户名”放在那里吗?
答案 0 :(得分:1)
试试这个:我添加了count(*) and the group by
$query = "SELECT username,time,
UNIX_TIMESTAMP(time) as timestamp,
UNIX_TIMESTAMP(active) as
activestamp,IP, count(*)
FROM ".$table_name." WHERE success='1'
group by username
ORDER BY active DESC";
看一下这个博客:http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/
答案 1 :(得分:0)
在COUNT(username)
子句中添加SELECT
,在查询末尾添加GROUP BY username
。
答案 2 :(得分:0)
SELECT
username,count(username)
FROM ".$table_name." WHERE success='1'
GROUP BY username
ORDER BY active DESC";