简体   繁体   中英

Adding or alter foreign key to a table in mysql

I am new beginner on sql query on mysql. I have table structure like this :

---------------------------------        ----------------------------
|  Table office                 |        |  Table_detail_complaint  |
---------------------------------        ----------------------------
|(PK)  id_office                |    ----|(PK) id_complaint         |
|      name                     |    |   |     complaint_2          |
|      complaint_1              |    |   |     time_response_2      |
|      time_response_complaint1 |    |   |     complaint_3          |
|      address                  |    |   |     time_response_3      |
|(FK)  id_complaint             |-----   ----------------------------
---------------------------------

I got a problem like this.

  1. I have success to create the table office. But, I forgot to put id_complaint as a foreign key. How can I ?
  2. How to create the detail_complaint_table ?
  3. After adding the fk, how can I make like this, if " a row in table office is deleted also delete a row on table_detail_complaint". Using cascade or what ?
  4. How to query complaint_1, complaint_2, complaint_3 on a select query, using JOIN or what ?
  5. This is the my big problem. I have a case that if the complaint is continuesly until complaint_N ?. Should I make complaint_4, complaint_5 ? Or, have another idea ?

You can create foreign key and cascading for child auto delete as per below-

ALTER TABLE table_office 
ADD CONSTRAINT FK_table_office_id_complaint FOREIGN KEY (id_complaint) 
REFERENCES table_detail_complaint (id_complaint) 
ON DELETE CASCADE;

For other part of your question share more details what kind of information you want to store and how you will use them..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM