SQL Order By id和Count star不起作用

时间:2015-08-10 17:16:17

标签: php mysql

我想获得所有记录的数量并获得最后记录:

   $sql_count_sms = "SELECT count(*) as total,content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
    $result_count_sms = mysql_query($sql_count_sms);
    $row_num_sms = mysql_fetch_assoc($result_count_sms);
    $num_sms     = $row_num_sms['total'];
    $last_my_sms = $row_num_sms['content'];

我可以获得多少条记录,但我无法获得最后content条记录。 它返回第一条记录!

我哪里错了?

下面的代码运行正常,但我认为count(*)mysql_num_rows更快。

    $sql_count_sms = "SELECT content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
    $result_count_sms = mysql_query($sql_count_sms);
    $row_num_sms = mysql_fetch_assoc($result_count_sms);
    $num_sms     = mysql_num_rows($result_count_sms);
    $last_my_sms = $row_num_sms['content'];

任何解决方案?

1 个答案:

答案 0 :(得分:1)

你想要的两个结果的粒度是不一样的。如果不使用子查询,则无法将聚合和单行组合到同一结果中。

将谷物视为结果的基本单位。使用GROUP BY和聚合函数可以影响" grain" ...表上每行一个结果行,或者按user_id等分组...将聚合函数视为a分组的形式。

你可以把它分成两个单独的陈述:

SELECT count(*) as total FROM android_users_sms WHERE user_id = :id;

SELECT * FROM android_users_sms WHERE user_id = :id ORDER BY id DESC LIMIT 1;

此外,根据您的问题,您可能希望将LIMIT 1ORDER BY结合使用,以获得最后一行。

现在,或许可以直观地反驳,这也应该有效:

SELECT count(*), content, id 
FROM android_users_sms 
WHERE user_id = :id 
GROUP BY id, content 
ORDER BY id 
LIMIT 1;`

这是因为我们改变了" grain"使用GROUP BY。这是真正的细微差别,我觉得这可能比我现在做的更好。

您也可以使用子查询执行此操作:

SELECT aus.*, 
(SELECT count(*) as total FROM android_users_sms WHERE user_id = :id) AS s1 
FROM android_users_sms AS aus 
WHERE user_id = :id ORDER BY id DESC LIMIT 1;