I recently started to study SQL and I’m trying to solve the problem:
I have a voting table db.votes
, it records the nickname, time and type. Like an event log. It now has 500,000 lines.
I need to record the total number of matches for each user (his total number of votes) in another db.users
table in the total_votes
column.
I can get the total votes for a user manually, like:
SELECT COUNT(*) FROM voters WHERE username="john";
Also I can write down the received value in other table.
UPDATE users SET total_votes = 20 WHERE username="john";
But how to do it automatically with a loop?
I tried to google similar methods and found several options with SQL-T, but I’m not sure if this will suit me.
2
Answers
You can use a correlated sub query for that, that would also work with multiple user
fiddle
You can do this in a number of ways. One of them looks like this:
Here is a DBFiddle demo