Skip to content

Instantly share code, notes, and snippets.

@DisplayName
Created September 27, 2012 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DisplayName/3793455 to your computer and use it in GitHub Desktop.
Save DisplayName/3793455 to your computer and use it in GitHub Desktop.
-- if you have all {Child, Parents, Keys}
function check_relation_type(child_table, child_column, parent_table, parent_column)
begin
declare child_cardinality double;
declare parent_cardinality double;
declare q varchar(255);
set q = concat('select count(distinct ', child_column ,') / count ( ', child_column, ') into @val from ', child_table , 'where ', child_column , ' is not null');
exec q;
set child_cardinality = @val;
set q = concat('select count(distinct ', parent_column ,') / count ( ', parent_column, ') into @val from ', parent_table , 'where ', parent_column , ' is not null');
exec q;
set parent_cardinality = @val;
if child_cardinality = 1 and parent_cardinality = 1 then
return 1:1
end if;
if child_cardinality = 1 then
return 1:M
end if;
if parent_cardinality = 1 then
return N:1
end if;
-- be aware of M:N
-- if you have Parent, Child with M:N type it would be (usually) normalized
-- in the following way: parent -> parent_child(parent_id, child_id) <- child
return M:N
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment