SQL返回Count +其他列

时间:2016-07-13 11:08:37

标签: mysql sql count

我有以下SQL查询:"SELECT * FROM table WHERE id = '$geo_name_id' ORDER BY timestamp DESC LIMIT 10 OFFSET $offset"

这样可以正常工作,但现在我还希望返回整个表WHERE id = 'geo_name_id中的行数(没有限制)。我尝试过这样的事情:

"SELECT COUNT(*) as totalExpectedItems, * FROM  story_img_vid WHERE id = '$geo_name_id' ORDER BY timestamp DESC LIMIT 10 OFFSET $offset"

然而,这似乎没有按预期工作,因为它只返回一行。

2 个答案:

答案 0 :(得分:1)

使用子查询:

"SELECT t.*,
        (SELECT COUNT(*) FROM table
         WHERE id = '$geo_name_id') as cnt
  FROM  table t
  WHERE t.id = '$geo_name_id'
  ORDER BY t.timestamp DESC
  LIMIT 10 OFFSET $offset"

cnt列将包含计数。

或者加入派生表:

"SELECT t.*,
        t2.cnt
 FROM table t
 JOIN(SELECT s.id,count(*) as cnt
      FROM table s GROUP BY s.id) t2
  ON(t.id = t2.id)
WHERE t.id = '$geo_name_id'
ORDER BY t.timestamp DESC
LIMIT 10 OFFSET $offset"

答案 1 :(得分:0)

这样做:

"SELECT COUNT(*) as totalExpectedItems, * FROM  story_img_vid WHERE id = '$geo_name_id'"