返回在数据表pdo中的记录数。

问题描述 投票:0回答:1

我有一个列表表:评论

comment: id_comment,comment, id_postcommented

comment
---------
comment A
commen  B
comment C
comment D
comment E
comment F
comment G
comment H
comment I
comment J

我需要检索评论的数量,如

`comment H: 8`

SQL

  select count(*) /* its not */
  from comments
  where id_comment = ?

我只是不知道如何才能得到它。

sql pdo
1个回答
1
投票

如果列 id_comment 是一个自动递增的id,那么你可以计算小于或等于你搜索的id。

select count(*)
from comments
where id_comment <= (select id_comment from comments where comment = 'comment H')

如果你想搜索的是 id_comment:

select count(*)
from comments
where id_comment <= :id_comment

或与 row_number() 窗口功能。

select t.rn
from (
  select *, row_number() over (order by id_comment) rn
  from comments
) t
where t.comment = 'comment H'

id_comment:

select t.rn
from (
  select *, row_number() over (order by id_comment) rn
  from comments
) t
where t.id_comment = :id_comment

如果您选择最后一个查询,那么您可以添加一个 WHERE 条款。

select t.rn
from (
  select *, row_number() over (order by id_comment) rn
  from comments
  where id_comment <= :id_comment
) t
where t.id_comment = :id_comment 

因为没有必要 id_comment大于 :id_comment 待处理。

另一种解决方案是 COUNT() 窗口功能。

select count(*) over (order by id_comment) 
from comments
where id_comment <= :id_comment 
order by id_comment desc limit 1

0
投票

如果我明白你想知道你的评论的数量,意思是如果它是第十条评论,那么10,那么你应该使用。行数

WITH MyTable AS -- you create a temp table ordered with rownumber corresponding to the line number.
(
    SELECT id_comment,
    ROW_NUMBER() OVER ( ORDER BY id_comment ) AS 'RowNumber'
    FROM comments
) 
-- now you get this row number
SELECT RowNumber, id_comment     
FROM MyTable 
WHERE id_comment = 'H'
© www.soinside.com 2019 - 2024. All rights reserved.