English 中文(简体)
mysql行计数器
原标题:mysql row counter
  • 时间:2011-02-11 14:58:49
  •  标签:
  • php
  • mysql

我有一张mysql表。它在id上有自动递增功能,但我经常删除行,所以数字到处都是。我需要取出最后n行,但由于删除,使用自动递增的id列的最大值的常见方法效果不佳。。。

1-他们是另一种进入最后50名的方式吗?

2-它们是通过实际行号来获取行的一种方法吗?所以如果我有4行标记为1,2,3,4删除第2行,那么它将变成1,2,3而不是1,3,4?

最佳回答
SELECT *
  FROM TABLE
 ORDER BY id DESC
 LIMIT 50

编辑

选择最后50个,但按id ASC排序

SELECT X.*
  FROM ( SELECT *
           FROM TABLE
          ORDER BY id DESC
          LIMIT 50
       ) X
 ORDER BY X.id
问题回答
SELECT ... ORDER BY id DESC LIMIT 50

1-首先获取行总数,如

SELECT COUNT(*) AS c FROM ...

然后使用

SELECT ..... LIMIT [start],[count]

2-一个想法是使用视图或过程,但这要困难得多,并且可能在没有其他方法可以避免的情况下使用

1-他们是另一种进入最后50名的方式吗?

SELECT * FROM table_name ORDER BY record_id DESC LIMIT 50

2-它们是通过实际行号来获取行的一种方法吗?所以如果我有4行标记为1,2,3,4删除第2行,那么它将变成1,2,3而不是1,3,4?

SELECT * FROM table_name

1-是的,但它很难看,你做了一个

SELECT whateveryouwant FROM table ORDER BY yourprimarykey DESC LIMIT 50

将行提取到数组中,并反转数组,在php中:

$r = mysql_query( SELECT * FROM table ORDER BY primarykey DESC LIMIT 50 );
$set = array();
while($row = mysql_fetch_assoc($r)) $set = $row;
$set = array_reverse($set);
foreach($set as $row) {
  // display row ...
}

2-你必须自己管理你的主键,这有点冒险。。。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签