Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count amount of rows referring to a foreign key in MySql?

Let's say a table like

CREATE TABLE `testdb`.`test` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

there are other tables may have foreign key referring to test.id column. The interesting thing is I don't know what table has such a foreign key and how many rows the table has.

now I want to calculate amount of rows dispersing in tables that have foreign key to test.id. Is it possible?

I think it's theoretically possible, otherwise MySql cannot do operations like ON DELETE CASCADE, DELETE SET NULL ...

like image 673
zx_wing Avatar asked Apr 20 '12 20:04

zx_wing


1 Answers

Displays all referenced tables with row counts

SELECT rc.table_name, t.TABLE_ROWS
FROM `REFERENTIAL_CONSTRAINTS` rc
INNER JOIN `TABLES` t ON t.TABLE_NAME = rc.TABLE_NAME
WHERE rc.REFERENCED_TABLE_NAME = "test"

Displays sum of all referenced tables row count

SELECT SUM(t.TABLE_ROWS) AS allReferencedTablesRowCount
FROM `REFERENTIAL_CONSTRAINTS` rc
INNER JOIN `TABLES` t ON t.TABLE_NAME = rc.TABLE_NAME
WHERE rc.REFERENCED_TABLE_NAME = "test"
like image 166
Nesim Razon Avatar answered Nov 02 '22 01:11

Nesim Razon