简体   繁体   English

计算MySQL表中给定值之前的行数

[英]Count number of rows until given value in MySQL table

I've searched for quite a while for an answer to this with no luck. 我已经搜索了很长一段时间来找到答案而没有运气。 Sorry if this is answered somewhere I couldn't find. 对不起,如果在某个地方找不到,我找不到。

I basically have a queue in a MySQL table and I need to tell people what number they are in the queue using PHP. 我基本上在MySQL表中有一个队列,我需要告诉人们使用PHP在队列中的数字。

Right now, I've got this, but all it does is count the number of rows in the table: 现在,我已经有了这个,但它只是计算表中的行数:

$rowquery = "SELECT * FROM restaurant_guests ORDER BY ID UNTIL";
if ($stmt = $mysqli2->prepare($rowquery)) {

/* execute query */
$stmt->execute();

/* store result */
$stmt->store_result();

printf("%d", $stmt->num_rows - 1);

/* close statement */
$stmt->close();
}               

Can someone please help point me in the right direction? 请有人帮我指点正确的方向吗? Thank you so much in advance! 非常感谢你提前! :) :)

If the ID field is the basis for your queue (ie higher the id higher the order in queue), then the query is as simple as counting the number of rows with id values <= to the user's id 如果ID字段是队列的基础(即,队列中的顺序越高,id越高),那么查询就像计算id值<=到用户id的行数一样简单

SELECT count(id) FROM restaurant_guests WHERE id <= ?

Here ? 在这? represents the id value you are searching for. 表示您要搜索的id值。

Wait a minute. 等一下。 Are the ID auto-incremented? ID是否自动递增? If only the guests with lower ID goes out of the queue first, then wouldn't it be better to just give: 如果只有ID较低的客户首先退出队列,那么只是给出:

answer = (the ID of user in question) - (lowest ID of the user in the queue) + 1

where the lowest ID of the user in the queue can be queried by: 可以通过以下方式查询队列中用户的最低ID:

SELECT ID from restaurant_guests ORDER BY ID LIMIT 1

At least, this approach will transfer a constant number of data from the DBMS in contrast with other approaches. 至少,与其他方法相比,这种方法将从DBMS传输恒定数量的数据。

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

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