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

半城伤御伤魂 提交于 2019-12-07 04:51:13

问题


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 ...


回答1:


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"



回答2:


if you have foreign-key-constraints defined you can read them from the database schema to see which columns in which tables are linked to your primary key.

edit: check this (on the left side select "Database metadata" -> "Find child tables")



来源:https://stackoverflow.com/questions/10253239/how-to-count-amount-of-rows-referring-to-a-foreign-key-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!