Delete two ID’s from different tables in the same query

Asked

Viewed 36 times

0

Good afternoon!
I have two tables: 1st question and second answer, and question_id is the key that allows connecting the two tables, being the foreign key in the "answer" table of the "question table".

When I enter a record, I cannot delete the record from the "question" table first, but rather from the "comment" table first".

As I developed a page the administrator can see all the results of the database, and manipulate them. One of the options is to eliminate the results one query to delete the last ID from your tables...


The ID I picked up by the URL:
$resposta_id = $_GET['resposta_id'];
but only the answer ID "$resposta_id", in query I thought to take somehow the last ID of the table "questionario" decreasing, but I could not form a query only with all this, and for the junction of the tables I had made:

select * from questionario left join resposta on questionario.pergunta_id=resposta.pergunta_id


If anyone has an idea of how to do, or even otherwise thank you!

  • I don’t understand very well, do you want to delete all records from the two tables? Or just the last record from each table?

  • In case the ID of both is question_id, when deleting one you want to delete from both tables?

  • @Matheusribeiro I’m sorry, I want to erase the last record of each table, as I said "the last ID"

  • @Mauroalexandre that’s right!

1 answer

2


whereas pergunta_id be a fk of the tables, you can make a INNER JOIN directly on delete.

DELETE t1,t2 FROM t1
    INNER JOIN
    t2 ON t2.ref = t1.id 

In this example it will delete all records where t2.ref be equal to t1.id.

Having the value of pergunta_id just add the clause WHERE

DELETE t1,t2 FROM t1
    INNER JOIN
    t2 ON t2.ref = t1.id 
    WHERE t1.id = '{pergunta_id}'

See the query working: http://www.sqlfiddle.com/#! 9/0a64b/2

  • Thank you for the answer, as soon as I can I’ll test the code!

  • 1

    It worked out! Thank you I did so $apagar="DELETE resposta, questionario from resposta
 INNER JOIN
 questionario ON questionario.pergunta_id = resposta.pergunta_id
 WHERE
 resposta.resposta_id = '".$resposta_id."'";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.