简体   繁体   English

PHP-SQL:以循环方式获取结果

[英]PHP - SQL: fetching results in round robin fashion

I have a table, which consists of 3 fields: 我有一个表,其中包含3个字段:

  • id ID
  • name 名称
  • status 状态

Every time I get the results, it should give me 5 names whose status = 1. Suppose the db contains following: 每次获得结果时,它应该给我5个状态= 1的名称。假设数据库包含以下内容:

id name status
1   A    1
2   B    1
3   C    0
4   D    1
5   E    0
6   F    0
7   H    1
8   I    1
9   J    1
10  K    1
11  L    1
12  M    0

1st time, fetch should return: A,B,D,H,I (5 records) 第一次,访存应返回:A,B,D,H,I(5条记录)
2nd time, fetch should return: J,K,L,A,B (5 records) 第二次,访存应返回:J,K,L,A,B(5条记录)

UPDATE : I don't want typical pagenation. 更新 :我不希望典型的分页。 Consider I have 12 available names from A1 to A12. 考虑一下我有12个可用的名字,从A1到A12。 The first fetch should return A1-A5, second fetch A6-A10 and third fetch A11, A12, A1, A2, A3. 第一次读取应返回A1-A5,第二次读取A6-A10,第三次返回A11,A12,A1,A2,A3。 So when I reach the end, I need to get records starting from the first to fill the 5 slots. 因此,当我到达结尾时,我需要从第一个开始获取记录以填充5个插槽。

i am doing it in php with mysql 我正在用mysql在php中进行操作

This looks like some sort of job allocation script? 这看起来像某种工作分配脚本吗?

You need 2 things: 您需要两件事:

  • the highest ID returned last time the script was run (lastID) 上次运行脚本时返回的最高ID(lastID)
  • a number larger than the maximum ID in the table (bigNum) 一个大于表中最大ID(bigNum)的数字

Then you can write your query as 然后,您可以将查询写为

SELECT
  id, name
FROM
  table
WHERE
  status=1
ORDER BY
  (bignum + id) MOD (bigNum + lastID + 1)
LIMIT 5

Shazaam!

Keep track of the ids of the records returned, and for the following queries do: 跟踪返回的记录的ID,对于以下查询,请执行以下操作:

select top 5 *
from (
    select top 5 * 
    from MyTable
    where status = 1 
        and id not in (1,2,4,7,8)
    order by name
    union 
    select top 5 * 
    from MyTable
    where status = 1 
    order by name
) a
$q = mysql_query("SELECT name FROM table WHERE status = 1 LIMIT 5);
while ($row = mysql_fetch_row($q))
{
  .... //first 5
}
$q = mysql_query("SELECT name FROM table WHERE status = 1 LIMIT 5,5);
while ($row = mysql_fetch_row($q))
{
  .... //second 5
}

this uses the offset functionality of mysql- think of it as pagination for your results. 它使用mysql的offset功能-将其视为您的结果的分页。

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

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