简体   繁体   中英

Update the quantity of a field in a column automatically based on data from another table in MySQL

It's quite simple really. Here's my database schema:

Table 1: posts

Columns: ID, contents, likes, dislikes

Table 2: posts_likes_dislikes

Columns: ID, user_id, post_id, like_or_dislike (1 or 0)

I want to update likes and dislikes in the table 1 depending on the information on table 2. I want a way to match the post_id (table 2) with the id (posts) and then count the amount of 1's and 0's. Based on that amount, I want to update likes and dislikes in table 1. I'm not entirely sure if this is possible. As much as possible, I don't want to use a cron job.

I would use a query like this:

UPDATE
  posts INNER JOIN (SELECT   post_id,
                             SUM(like_or_dislike=1) likes,
                             SUM(like_or_dislike=0) dislikes
                    FROM     posts_likes_dislikes
                    GROUP BY post_id) l
  ON posts.ID = l.post_id
SET
 posts.likes = l.likes,
 posts.dislikes = l.dislikes

Please see fiddle here .

Edit: if you need to update your posts table dinamically with a trigger, you could use a solution like this:

CREATE TRIGGER after_insert
BEFORE INSERT ON posts_likes_dislikes
FOR EACH ROW
  UPDATE posts
  SET
    posts.likes = posts.likes + (new.like_or_dislike=1),
    posts.dislikes = posts.dislikes + (new.like_or_dislike=0)
  WHERE
    posts.ID = new.post_id;

(please notice that, depending on how your database is structured, you might also want to consider an update and a delete trigger).

Fiddle is here .

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