简体   繁体   English

向mysql中的表添加或更改外键

[英]Adding or alter foreign key to a table in mysql

I am new beginner on sql query on mysql.我是 mysql 上 sql 查询的新手。 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.但是,我忘了把 id_complaint 作为外键。 How can I ?我怎样才能 ?
  2. How to create the detail_complaint_table ?如何创建 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".添加fk后,如果“表office中的一行被删除也删除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 ?如何使用 JOIN 或什么在选择查询上查询投诉_1、投诉_2、投诉_3?
  5. This is the my big problem.这是我的大问题。 I have a case that if the complaint is continuesly until complaint_N ?.我有一个案例,如果投诉一直持续到投诉_N ?。 Should I make complaint_4, complaint_5 ?我应该投诉_4,投诉_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..对于您问题的其他部分,请分享更多详细信息,您要存储什么样的信息以及您将如何使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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