我有以下 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"
但是这似乎并没有像预期的那样工作,因为它只返回一行。
最佳答案
使用子查询:
"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"
关于mysql - SQL 返回计数 + 其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349970/