2012-05-07 81 views
2

我有一個名爲replies的表,它有一個名爲topic_id的列。SQL Server獲取行數

我想要做的是計算有多少行具有topic_id 1.

我試圖

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

但在這種情況下,我不知道這是否是一個有效的查詢。如果是這樣,我怎樣才能將它拉回到我的php代碼中名爲$num_rows的變量中?

說明:*實際上是我介紹的前綴。

回答

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 
+0

,然後做$ NUM_ROWS = $行[ 'NUM_ROWS']? – Grigor

+0

你想把它拉回到PHP? – zimdanen

+0

@zimdanen是的,我 – Grigor