dongye9991 2016-04-10 04:21
浏览 47
已采纳

两个表,一个是tag_t,其中包含tagName,另一个是book_t。 当我将新标签添加到tag_t时,我希望在book_t中添加新列

Database scheme:

enter image description here

If i create a new tag then book_table create a new column automatically.
Is it possible?

  • 写回答

1条回答 默认 最新

  • doutao4480 2016-04-10 04:38
    关注

    Create a relationship table instead.

    CREATE TABLE book_tag_t
    ( book_id   INT UNSIGNED NOT NULL
    , tag_id    INT UNSIGNED NOT NULL
    , PRIMARY KEY (book_id,tag_id)
    , CONSTRAINT book_tag_t_book FOREIGN KEY (book_id) REFERENCES book_t (id)
         ON DELETE CASCADE ON UPDATE CASCADE
    , CONSTRAINT book_tag_t_tag FOREIGN KEY (tag_id) REFERENCES tag_t (id)
         ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB
    

    To relate a `tag\ to a \book`

    INSERT INTO book_tag_t (book_id, tag_id) VALUES ( 2, 14 );
    

    To get all of the books related to a specific tag:

    SELECT b.id
      FROM book_t b
      JOIN book_tag_t r
        ON r.book_id = b.id
      JOIN tag_t t
        ON t.id = r.tag_id
     WHERE t.tagName = 'Science' 
     ORDER BY b.id
    

    To address the question you asked, "Is it possible?"

    You could probably get something working. That will require a DDL ALTER TABLE statement to be executed on book_table, and that's going to be expensive in terms of concurrency (exclusive locks), and resources (creating a new copy of the table). And you can't do an ALTER TABLE in a trigger. If you actually need functionality like this, the required SQL would be better executed from the application, not from something "automatic" in the database.

    What are you going to do when the number of rows in `tag_t` exceeds the number of columns allowed in a table? When a row is deleted? or updated?

    It's a horrible idea.

    The normal relational approach is to add a third table, a relationship table, to resolve the many-to-many relationship between `book` and `tag`. As illustrated in the first part of this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决