Remember that:
When you join two tables on a non-unique value, you end up with all possible combinations of the rows containing the matching fields.
table_name
andtable_schema
are not a unique value inkey_column_usage
.
As such, in situations where there is more than one row in key_column_usage
for a given table, you're ending up with multiple copies of the corresponding row from statistics
. This is messing up your pk_length
.
You will most likely need to split this up into two separate queries: one for pk_length
and the other for key_count
.