I'm trying to update my database. My USER table has a column NbFollower that should hold the number of people who follow this user.
So I need to count that number from another table FOLLOWING_USER.
The USER.UserID = 1 appears 4 times in FOLLOWING_USER. That means he has 4 followers.
How can I use the function UPDATE and a COUNT at the same time, for each people ?
UPDATE [USER]
SET NbFollower = (SELECT count(User)
FROM FOLLOWING_USER FU
INNER JOIN [USER] U ON FU.[User] = U.UserID)
This returns "13" for ALL my users (13 is the total number of rows in FOLLOWING_USER)
So I need something like this, but automatised for all my users:
SELECT COUNT([User])
FROM FOLLOWING_USER
WHERE [User] = 1
EDIT: here my table USER
CREATE TABLE [USER]
(
UserID int IDENTITY(1, 1) PRIMARY KEY,
URL varchar(50) NOT NULL,
Name varchar(20) NOT NULL,
Password varchar(50) NOT NULL,
Email varchar(100) NOT NULL,
Age int NOT NULL,
Gender char(1) NOT NULL,
Location varchar(50) NOT NULL,
Description varchar(200) NULL,
NbFollower int NULL DEFAULT 0,
Rating int NULL DEFAULT 0
);
ALTER TABLE [USER]
ADD ShareoutwardzID INT
FOREIGN KEY REFERENCES SHAREOUTWARDZ(ShareoutwardzID),
CONSTRAINT Age CHECK (Age>=18);
INSERT INTO [USER] (Name, URL, Password, Email, Age, Gender, Location, Description, Rating)
VALUES
('lily', '/NAME', 'azertyuop123', 'lily@hotmail.com', 21, 'F', 'USA', NULL, 4);
Here my table FOLLOWING_USER:
CREATE TABLE FOLLOWING_USER
(
[User] int NOT NULL FOREIGN KEY REFERENCES [USER](UserID),
Follower int NOT NULL FOREIGN KEY REFERENCES FOLLOWER(UserID),
);
INSERT INTO FOLLOWING_USER([User], Follower)
VALUES (1, 9), (2, 9), (4, 9), (6, 9);