简体   繁体   English

SQL自我计算字段

[英]SQL self calculated field

I have two tables which are connected by m2m relationship. 我有两个表通过m2m关系连接。

CREATE TABLE words 
    (
    id INT PRIMARY KEY, 
    word VARCHAR(100) UNIQUE, 
    counter INT
    )

CREATE TABLE urls 
    (
    id INT PRIMARY KEY, 
    url VARCHAR(100) UNIQUE
    )

CREATE TABLE urls_words 
    (
    url_id INT NOT NULL REFERENCES urls(id), 
    word_id INT NOT NULL REFERENCES words(id)
    )

and i have counter field in words table. 我在单词表中有计数器字段。 How can i automize proccess of updating counter field which is responsible for calculating how much rows stored in urls_words with particular word. 如何自动更新计数器字段的过程,该计数器字段负责计算urls_words中存储的特定字的行数。

I would investigate why you want to store this value. 我会调查你为什么要存储这个值。 There may be good reasons, but triggers complicate databases. 可能有充分的理由,但会触发数据库复杂化。

If this is a "load-then-query" database, then you can update the count when you load data -- presumably at some frequency such as once a day or once a week. 如果这是一个“加载然后查询”数据库,那么您可以在加载数据时更新计数 - 可能是某些频率,例如每天一次或每周一次。 You don't need to worry about triggers. 您无需担心触发器。

If this is a transactional database, then triggers would be needed and these add complexity to the processing. 如果这是一个事务性数据库,则需要触发器,这会增加处理的复杂性。 They also lock tables when you might not want them locked. 当您可能不希望它们被锁定时,它们也会锁定表。

An alternative is to have an index on urls_words(word_id, url_id) . 另一种方法是在urls_words(word_id, url_id)urls_words(word_id, url_id)索引。 This would greatly speed the calculation of the count when you need it. 这将大大加快您需要时计算的次数。 It also does not require triggers or locks on multiple table during an update. 在更新期间,它也不需要多个表上的触发器或锁。

在urls_words表上创建一个触发器,每次进行更改(即更新,插入,删除)时,都会更新单词表上的计数器列。

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

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