2

我有一个名为的表replies,它有一个名为topic_id.

我想做的是计算topic_id为1的行数。

我试过

SELECT COUNT(*) 
FROM [***].[replies] 
WHERE [***].[topic_id] = '1'

但在这种情况下,我不知道这是否是一个有效的查询。如果是,我怎样才能将它拉回到$num_rows我的 php 代码中调用的变量中?

注意:*实际上是我介绍的前缀。

4

1 回答 1

3

像这样的东西应该工作:

--declare the variable
DECLARE @num_rows INT

--get the total number of rows
SELECT @num_rows = COUNT(*) FROM replies WHERE topic_id = 1

--get a distinct count of rows (if for some reason you need it)
SELECT @num_rows = COUNT(DISTINCT reply_id) FROM replies WHERE topic_id = 1

--return the result set
SELECT @num_rows AS num_rows

如果您只想返回一个名为num_rows虽然的列,这将是一种更有效的方法:

SELECT COUNT(*) AS num_rows FROM replies WHERE topic_id = 1
于 2012-05-07T20:38:15.137 回答