developer tip

테이블 행 수를 얻는 가장 효율적인 방법

optionbox 2020. 11. 16. 08:08
반응형

테이블 행 수를 얻는 가장 효율적인 방법


현재 6 백만 개가 넘는 행이있는 데이터베이스가 있으며 증가하고 있습니다. 나는 현재 SELECT COUNT (id) FROM table을 수행합니다. 내 사용자에게 숫자를 표시하기 위해 데이터베이스가 커지고 있으며 숫자를 표시 할 수있는 것 외에는 모든 행을 저장할 필요가 없습니다. 표시 할 auto_increment 값을 선택하여 데이터베이스에서 대부분의 행을 지울 수있는 방법이 있습니까? 사용 LAST_INSERT_ID()이 작동하지 않는 것 같습니다.


레코드 (행) 수를 얻는 것에 관한 것이라면 다음을 사용하는 것이 좋습니다.

SELECT TABLE_ROWS
FROM information_schema.tables 
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB 
  AND table_schema = DATABASE();      -- See comment below if > 1 DB

(적어도 MySQL의 경우) 대신.


다음은 AUTO_INCREMENT테이블 의 다음 을 찾는 가장 효과적인 방법 입니다. 이는 잠재적으로 큰 information_schema데이터베이스를 쿼리 할 필요가 없기 때문에 수백만 개의 테이블이있는 데이터베이스에서도 빠릅니다 .

mysql> SHOW TABLE STATUS LIKE 'table_name';
// Look for the Auto_increment column

그러나 쿼리에서이 값을 검색해야하는 경우 information_schema데이터베이스로 이동해야합니다.

SELECT `AUTO_INCREMENT`
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_SCHEMA = 'DatabaseName'
AND    TABLE_NAME   = 'TableName';

이 시도

이 SQL을 실행하십시오.

SHOW TABLE STATUS LIKE '<tablename>'

필드의 값을 가져옵니다. Auto_increment


왜 아무도 다음을 제안하지 않았는지 잘 모르겠습니다. 이렇게하면 SQL 만 사용하여 auto_increment 값을 얻습니다 (PHP를 사용할 필요 없음 mysql_fetch_array).

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE TABLE_NAME = 'table'

선택 쿼리를 작성하여 직접 최대 수를 얻으면 쿼리가 잘못된 값을 제공 할 가능성이 있습니다. 예를 들어 테이블에 5 개의 레코드가 있으므로 증가 ID는 6이되고 레코드 번호 5를 삭제하면 테이블에는 최대 ID가 4 인 4 개의 레코드가 있습니다.이 경우 다음 증가 ID로 5를 얻게됩니다. 당신은 mysql 정의 자체에서 정보를 얻을 수 있다는 것을 강조했습니다. PHP에서 다음 코드를 작성하여

<?
$tablename      = "tablename";
$next_increment     = 0;
$qShowStatus        = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult  = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );

$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];

echo "next increment number: [$next_increment]";
?>

SELECT id FROM table ORDER BY id DESC LIMIT 1자동 증가 ID가 아닌 최대 ID를 반환 할 수 있습니다. 둘 다 일부 조건에서 다릅니다


"상태 표시"에 대한 권한이없는 경우 가장 좋은 방법은 두 개의 트리거와 10 억 개의 레코드 테이블의 행 수를 유지하는 새 테이블을 만드는 것입니다.

예:

TableA >> Billion Records
TableB >> 1 열 1 행

TableA (InsertTrigger)에 삽입 쿼리가있을 때마다 TableB 1 씩 행 값 증가
TableA (DeleteTrigger)에 삭제 쿼리가있을 때마다 TableB에서 행 값 1 씩 감소


information_schema 제안 옆에 다음이 있습니다.

SELECT id FROM table ORDER BY id DESC LIMIT 1

id 필드에 인덱스가있는 경우에도 매우 빠릅니다 (auto_increment의 경우 여야한다고 생각합니다).


$next_id = mysql_fetch_assoc(mysql_query("SELECT MAX(id) FROM table"));
$next_id['MAX(id)']; // next auto incr id

도움이 되길 바랍니다 :)


제어 장치

SomeNameModel::_getNextID($this->$table)

모델

class SomeNameModel extends CI_Model{

private static $db;

function __construct(){
  parent::__construct();
  self::$db-> &get_instance()->db;
}


function _getNextID($table){
  return self::$db->query("SHOW TABLE STATUS LIKE '".$table."' ")->row()->Auto_increment;
}

... other stuff code

}

이 답변 중 어느 것도 옳지 않은 것 같습니다. 나는 그들 모두를 시도했다. 내 결과는 다음과 같습니다.

Sending query: SELECT count(*) FROM daximation
91
Sending query: SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'
96
Sending query: SHOW TABLE STATUS LIKE 'daximation'
98
Sending query: SELECT id FROM daximation ORDER BY id DESC LIMIT 1
97

here's the screenshot: https://www.screencast.com/t/s8c3trYU

Here is my PHP code:

$query = "SELECT count(*) FROM daximation"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SHOW TABLE STATUS LIKE 'daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[10]);

$query = "SELECT id FROM daximation ORDER BY id DESC LIMIT 1"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

Couldn't you just create a record in a separate table or whatever with a column called Users and UPDATE it with the last inserted id on User Registration?

Then you would just check this field with a simple query.

It might be rough but it would work perfectly.

참고URL : https://stackoverflow.com/questions/933565/most-efficient-way-to-get-table-row-count

반응형