简体   繁体   中英

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. There is a foreign key product_id in the comment table referencing the product table. 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?

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) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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