developer tip

MySQL-한 쿼리에서 테이블 당 모든 행을 계산하는 방법

optionbox 2020. 11. 13. 08:04
반응형

MySQL-한 쿼리에서 테이블 당 모든 행을 계산하는 방법


모든 테이블에 몇 개의 행이 있는지 알아보기 위해 DB를 쿼리하는 방법이 있습니까?

table1 1234
table2 222
table3 7888

당신이 조언 할 수 있기를 바랍니다


SELECT 
    TABLE_NAME, 
    TABLE_ROWS 
FROM 
    `information_schema`.`tables` 
WHERE 
    `table_schema` = 'YOUR_DB_NAME';

위의 내용은 근사치를 제공하지만 정확한 개수를 원하면 두 단계로 수행 할 수 있습니다. 먼저 다음과 같은 쿼리를 실행합니다.

select concat("select '",table_name,"', count(*) from ",table_name,";") 
from `information_schema`.`tables` 
WHERE `table_schema` = '[your schema here]';

그러면 데이터베이스의 각 테이블에 대해 하나씩 SQL 문 목록이 생성되고 정확한 개수를 얻기 위해 실행할 수 있습니다.


이것은 당신에게 정확한 테이블 이름을 제공하고 단일 목록에 포함됩니다.

SELECT CONCAT('SELECT ''',table_name,''', COUNT(*) FROM ', table_name, ' union all') 
      FROM information_schema.tables WHERE table_schema = 'clw';

SELECT 
    table_name, 
    table_rows 
FROM 
    INFORMATION_SCHEMA.TABLES

위의 정보 와이 게시물 을 하나의 쿼리 집합으로 합성하면 정확한 행 수를 제공하는 자체 작성 쿼리가 생성됩니다.

SET @tableSchema = 'my_schema';
SET SESSION group_concat_max_len = 10000000;
SET @rowCounts = (
  SELECT group_concat(CONCAT('SELECT ''',TABLE_NAME,''', COUNT(*) FROM ', TABLE_NAME) SEPARATOR ' union all ')
  FROM information_schema.tables WHERE table_schema = @tableSchema
);
PREPARE statement FROM @rowCounts;
EXECUTE statement;

-- don't run dealloc until you've exported your results ;)
DEALLOCATE PREPARE statement;

select sum(cnt) from
(
select count(*) as cnt from table1
union ALL
select count(*) as cnt from table2
union ALL
select count(*) as cnt from table3 
)t1

아마도 테이블 만 원하고 뷰를 원치 않는 경우 이것을 원할 것입니다.

SELECT TABLE_NAME, TABLE_ROWS
FROM   `information_schema`.`tables` 
WHERE  `table_schema` = 'schema'
       AND TABLE_TYPE = 'BASE TABLE';

참고 URL : https://stackoverflow.com/questions/2692340/mysql-how-to-count-all-rows-per-table-in-one-query

반응형