3
I’m having a problem that I didn’t find anything in Google (maybe I didn’t know to ask him)
Just imagine the following:
I have 11 tables, one call tbl_pai and 10 other calls tbl_filha1, tbl_filha2, tbl_daughter{n}.
In the daughter tables has a field called id_pai and a Constraint (CONSTRAINT fk_filha_com_pai FOREIGN KEY (id_pai) REFERENCES tbl_pai(id))
That is, 10 tables that have foreign keys referenced to the main table
The question is: How can I elegantly test whether or not I can remove a tuple from the main table? I could only think of two options: Try to delete the parent record and treat the error if the record is referenced in another table, or, make a COUNT in all daughter tables to know if there is dependency.
I need that information to decide whether or not to release a DELETE in my application. If the record has no reference, I display the button, if not I hide the button. The problem is that this button is in a listing (of 'parent' records) and this check needs to be done for each record. I did using the COUNT but was extremely slow as the 'parent' table has over a million records.
There is a less costly method?
Personal thank you.
how did you make your Count?? post the Query you had made
– Thomas Lima
Okay but I need to stop using Count. In the example above I spoke of imaginary tables, the query I will post is the real one:
– Gustavo
SELECT 
 (SELECT COUNT(t.id) FROM telemetria t WHERE t.id_sistema = s.id) +
 (SELECT COUNT(a.id) FROM alerta a WHERE a.id_sistema = s.id) + 
 (SELECT COUNT(c.id) FROM controle c WHERE c.id_sistema = s.id) + 
 (SELECT COUNT(cs.id) FROM cliente_sistema cs WHERE s.id_sistema = s.id) AS qtde 
 FROM sistema s 
 WHERE s.id = 1;
The telemetry table is very voluminous. The list in the application is systems and I need to check whether or not I provide the button to delete the system.– Gustavo
Please take a look at this question: http://dba.stackexchange.com/questions/23041/is-there-a-way-to-test-whether-delete-will-fail-dueto-constraints
– Pedro Teles