I have these tables:
CREATE TABLE User(
Username varchar(15) NOT NULL,
Name varchar(20) DEFAULT '',
Surname varchar(20) DEFAULT '',
Email varchar(30) DEFAULT '',
City varchar(20) DEFAULT '',
Description varchar(1000) DEFAULT '',
userID INTEGER NOT NULL,
Primary key(Username, userID),
Foreign key(userID) references Followers(userID)
);"
CREATE TABLE Followers(
userID INTEGER NOT NULL,
usernameFollower varchar(15),
Primary key(userID),
Foreign key(usernameFollower) references User(Username)
);"
CREATE TABLE Post(
Username varchar(15) NOT NULL,
userID INTEGER NOT NULL,
Date DATETIME NOT NULL,
Message VARCHAR(500) NOT NULL,
Primary key(Username, Date),
Foreign key(Username) references User(Username)
);"
I need to get with a query a list with all the users in User, and for each user the date of the latest post they made and the number of followers they have.
For example, the output have to be like this:
USERNAME LATEST POST FOLLOWERS
user1 2011/11/11 18:30:11 5
user2 2011/10/05 17:30:00 1
user3 2010/05/11 18:30:11 90
user4 2011/11/11 18:30:11 5
I can’t figure how to make it..I presume for the count of the followers I need to use COUNT(), but how can I link it to the latest post of the user? Is possible in just one query? Or do I need to use views?
Thanks in advance, best regards.
You need to join across all 3 tables via the userID. You can then select the latest post date by grouping by user id. Originally, I also joined onto the Followers table, but this has an unintended side-effect, so…
Something like:
Should work.
Please note that my query is assuming that a user has posted. If they haven’t then change the INNER JOIN to a LEFT JOIN.
The reason the original query doesn’t work is that it matches a row in Post for each user, and a row in Followers for each user – thus multiplying the number of results. Instead, we can use a subquery to select the count of followers with the matching userid in the User table.
HOWEVER… this only counts the total number of followers a user has, not the number of followers for a post. The reason for this is because you have only linked a follower to a user. You’d also need to have a relationship between Follower and Post.
You can do this in a number of ways; you can create a PostFollower table consisting of PostId and UserId (so you can see which user has followed each post) or you can add a PostId to the Follower table, and store the follower userId and the PostId, allowing you to store which user followed which posts.