以下查询正在做我需要的事情:
SELECT assign.from_uid, assign.aid, assign.message, curriculum.asset,
curriculum.title, curriculum.description
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum
ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13 AND assign.status = 1
GROUP BY assign.from_uid, assign.to_uid, assign.nid
ORDER BY assign.created DESC
现在我需要得到结果的总行数。例如,如果它显示5行,则o / p应该类似于我预期的o / p。我试过的查询如下:
SELECT count(description) FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13 AND assign.status = 1
GROUP BY assign.from_uid, assign.to_uid, assign.nid
ORDER BY assign.created DESC
我预期的o / p:
count(*)
---------
5
我当前的o / p:
count(*)
---------
6
2
5
6
6
答案 0 :(得分:2)
最简单的解决方案是
GROUP BY
查询放入子选择SELECT COUNT(*)
FROM (
SELECT assign.from_uid
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13
AND assign.status = 1
GROUP BY
assign.from_uid
, assign.to_uid
, assign.nid
) q
它已经准备好获取正确结果所需的内容
from_uid, to_uid, nid
现在你不想计算每个组合有多少记录(正如你在你的例子中所做的那样),但是有多少独特的(不同于任何人?)组合。
对此的一个解决方案是我提出的子选择,但使用DISTINCT
子句的等效语句可能更全面。
SELECT COUNT(*)
FROM (
SELECT DISTINCT assign.from_uid
, assign.to_uid
, assign.nid
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13
AND assign.status = 1
) q
请注意,我个人的偏好是GROUP BY
解决方案。
答案 1 :(得分:0)
要获取查询的行数,请执行以下操作:
SELECT COUNT(*) as RowCount FROM (--insert other query here--) s
在你的例子中:
SELECT COUNT(*) as RowCount FROM (SELECT a.from_uid
FROM assignment a
INNER JOIN curriculum_topics_assets c ON a.nid = c.asset
WHERE a.to_uid = 13
AND a.status = 1
GROUP BY a.from_uid, a.to_uid, a.nid
) s
请注意,我删除了对行数没有影响的内容,以使查询运行得更快。
答案 2 :(得分:-1)
您应该使用COUNT(*)
代替count(description)
。请看:http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/