简体   繁体   English

在 MYSQL 中的父表中存储子项数的最佳方法

[英]Best way to store number of children in parent table in MYSQL

I am trying to implement a simple product system in MYSQL, where a product can have many comments.我试图在MYSQL中实现一个简单的产品系统,其中一个产品可以有很多评论。 There is a foreign key product_id in the comment table referencing the product table.引用产品表的评论表中有一个外键product_id。 I want to store the number of comments of the product as a field in the product table for sorting purpose.我想将产品的评论数量存储为产品表中的一个字段以进行排序。 It can be achieved by creating two triggers on the comment table like this可以通过像这样在评论表上创建两个触发器来实现

DELIMITER $$
CREATE TRIGGER comment_incr_trig
AFTER INSERT ON `COMMENT` FOR EACH ROW
begin
    UPDATE PRODUCT SET NUM_OF_COMMENT = NUM_OF_COMMENT + 1 WHERE ID = NEW.PRODUCT_ID;
END;
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER comment_decr_trig
AFTER DELETE ON `COMMENT` FOR EACH ROW
begin
    UPDATE PRODUCT SET NUM_OF_COMMENT = NUM_OF_COMMENT - 1 WHERE ID = OLD.PRODUCT_ID;
END;
$$
DELIMITER ;

However, is there any mechanism in MYSQL that can directly bind one field in the parent table to the number of children without using trigger?但是,MYSQL中有没有什么机制可以不使用触发器直接将父表中的一个字段绑定到子表的数量?

Many Thanks.非常感谢。

I would generally recommend against storing such derived information .我通常建议不要存储此类派生信息 You can easily compute on the fly in your queries whenever you need it.您可以在需要时轻松地在查询中动态计算。

To avoid repeatedly typing the same query again, one solution would be to create a view:为了避免再次重复输入相同的查询,一种解决方案是创建一个视图:

create view product_view(id, num_of_comments) as
select
    p.id,
    c.num_of_comments
from product p
left join (
    select product_id, count(*) num_of_comments
    from comment
    group by product_id
) c on c.product_id = p.id

You can expand the view with more columns coming from the product table (I could not add more since the only column that is showned in your question is product(id) ).您可以使用来自product表的更多列扩展视图(我无法添加更多列,因为您的问题中显示的唯一列是product(id) )。

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

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