简体   繁体   English

SQL检查下一行是否不存在

[英]SQL check if next row doesn't exist

I have an MsSQL server and what I am doing is selecting rows from the table. 我有一台MsSQL服务器,我正在做的是从表中选择行。 Currently I have two rows so I was wondering how would I check if there are no other rows after second one without making another query? 当前我有两行,所以我想知道如何在第二个之后没有其他查询的情况下检查是否没有其他行?

For example 例如

table users 表用户

id    name    pass

1     joe     123

2     bob     abc

How would I check if there is no row after 2 with just a query? 我如何仅查询就检查2之后是否没有行? I am willing to combining it with my current query, which just selects the data. 我愿意将其与当前查询结合起来,后者仅选择数据。

You can return the number of rows in your query as another column: 您可以将查询中的行数作为另一列返回:

SELECT id, name, pass, count(*) over () as rows
FROM users

Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. 请记住,这是在告诉您查询返回的行数,而不是表中的行数。 However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n" 但是,如果您在选择中指定“ TOP n”,则“行”列将为您提供如果没有“前n个”将返回的行数

If you're trying to paginate the trick is to query one more record than you actually need for the current page. 如果要分页,诀窍是要查询比当前页面实际需要多的一条记录。 By counting the result ( mysql_num_rows ) and comparing that to your page size, you can then decide if there is a 'next page'. 通过计算结果( mysql_num_rows )并将其与页面大小进行比较,然后可以确定是否存在“下一页”。

If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. 如果您使用的是mysql,则还可以在查询中使用SQL_CALC_FOUND_ROWS() ,该查询将计算不带LIMIT子句将返回的行数。 Maybe there is an equivalent for that in MsSQL? 也许在MsSQL中有一个等效的功能?

I assume that you are inserting manually the first 2 rows of your table. 我假设您正在手动插入表的前2行。

According to that, my idea is to just do a select where the id is more than 2 like this: 据此,我的想法是仅选择一个id大于2的对象,如下所示:

SELECT * FROM users WHERE id > 2;

I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2. 我还假设您正在使用PHP,因此如果未找到数据, mysql_num_rows将返回0 ,否则它将返回查询的行数,现在您知道需要做while或一些循环才能检索到数据在编号2之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM