简体   繁体   English

SQL在MySQL和PHP中为多个类别实现nn关系

[英]SQL to implement n-n relationship for Multiple Categories in MySQL & PHP

I wish to know what SQL is needed to be passed to implement multiple categories for an article. 我想知道为实现文章的多个类别需要传递什么SQL。

I have created 3 tables. 我已经创建了3张桌子。

ARTICLES:
id, title, content

CATEGORIES:
id, name

RELATION:
article_id, cat_id

I am successfully able to create the first two tables, and store data in them when user submits the form. 我可以成功创建前两个表,并在用户提交表单时将数据存储在其中。 But, I have no clue how to update the RELATION table. 但是,我不知道如何更新RELATION表。 I searched on stackoverflow, and I learned that I need to use a many to many relationship. 我搜索了stackoverflow,并了解到我需要使用多对多关系。 I have idea about it. 我对此有想法。 But, I do not know how to do it practically ie the SQL. 但是,我不知道如何实际执行该操作,即SQL。

The Categories are obviously added while the post is published, So i need to update this table only after the first two tables have been updated. 显然,在发布文章时添加了类别,因此我仅在更新了前两个表后才需要更新此表。

If someone can guide me to a tutorial or in the right direction I shall be greatful. 如果有人可以指导我指导教程或朝正确的方向发展,我将非常感激。

This should be taken care of by your SQL DBMS. 您的SQL DBMS应该注意这一点。 For example, if you set your relationship's foreign keys to cascade delete or update, when something changes in the parent, the children will also be deleted/updated. 例如,如果将关系的外键设置为级联删除或更新,则当父项发生更改时,子项也将被删除/更新。 Can you give me an example of an update that you would expect to make to the first two tables and the resulting update to the RELATION table? 您能否举一个例子,说明您希望对前两个表进行的更新以及对RELATION表的更新?

Assuming that post and article are synonyms, then each time a new post is published and its category is determined you need to 'INSERT' a record into 'RELATION' table. 假设帖子文章是同义词,那么每次发布新帖子并确定其类别时,您都需要将记录“插入”到“ RELATION”表中。

When you originally create tables you will need to identify Primary and Foreign keys (CONSTRAINTS) and (if so desired) specify whether CASCADE should be enabled. 最初创建表时,您需要标识键和键(CONSTRAINTS),并(如果需要)指定是否应启用CASCADE

Apparently you already know how to CREATE tables and INSERT rows. 显然,您已经知道如何CREATE表和INSERT行。

You may want to Google for PRIMARY KEY, FOREIGN KEY, CASCADE ON DELETE in conjunction with MYSQL and PHP. 您可能希望Google与MYSQL和PHP一起使用PRIMARY KEY,FOREIGN KEY,CASCADE ON DELETE。

Also see if the following helps any: How do I use on delete cascade in mysql? 另请参阅以下内容是否有帮助: 如何在mysql中的删除级联上使用? .

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

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