I'm pretty new to the world of databases and SQL.
I'm trying to build a system for users to submit posts and like posts. I've been looking at a few similar questions on this site, reading about third normal form, etc. and I think I have a pretty solid DB schema at this point:
CREATE TABLE IF NOT EXISTS USERPROFILES (
ID INT AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(64) NOT NULL,
EMAIL_ADDRESS VARCHAR(255) NOT NULL,
COUNTRY_CODE CHAR(2) NOT NULL,
CREATED_DATE DATETIME(9) NOT NULL
)
ALTER TABLE USERPROFILES ADD CONSTRAINT USERPROFILES_USERNAME_UNIQUE UNIQUE (USERNAME)
ALTER TABLE USERPROFILES ADD CONSTRAINT USERPROFILES_EMAIL_ADDRESS_UNIQUE UNIQUE (EMAIL_ADDRESS)
CREATE TABLE IF NOT EXISTS USERPOSTS (
ID INT AUTO_INCREMENT PRIMARY KEY,
THREAD_ID INT NOT NULL,
PARENT_POST_ID INT NULL,
PROFILE_ID INT NOT NULL,
WRITTEN_TEXT VARCHAR(500) NOT NULL,
MEDIA_LOCATION VARCHAR(255) NULL,
CREATED_DATE DATETIME(9) NOT NULL,
CONSTRAINT FK_USERPOSTS_PROFILE_ID__ID FOREIGN KEY (PROFILE_ID) REFERENCES USERPROFILES(ID) ON DELETE RESTRICT ON UPDATE RESTRICT
)
CREATE TABLE IF NOT EXISTS USERVOTES (
POST_ID INT,
PROFILE_ID INT,
CREATED_DATE DATETIME(9) NOT NULL,
CONSTRAINT pk_UserVotes PRIMARY KEY (POST_ID, PROFILE_ID),
CONSTRAINT FK_USERVOTES_POST_ID__ID FOREIGN KEY (POST_ID) REFERENCES USERPOSTS(ID) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT FK_USERVOTES_PROFILE_ID__ID FOREIGN KEY (PROFILE_ID) REFERENCES USERPROFILES(ID) ON DELETE RESTRICT ON UPDATE RESTRICT
)
Now what I want to do is perform a single query for my application to fetch all USERPOSTS
with a given THREAD_ID
(on behalf of a requesting user), but also join with the USERVOTES
and USERPROFILES
tables such that I can get a list of posts combined with the following data:
- total like count for the post
- if the requesting user liked the post or not
- the username of the submitter of the post (not just their userprofile ID)
With this I can render everything I need in the application.
Can anyone help construst a single query like this given my table schema? I'm assuming I will need at least two INNER JOINs (one on USERVOTES and one on USERPROFILE) as well as a COUNT on the USERVOTES (but also, in addition, how do I query USERVOTES with a WHERE for a specific requesting USERID)?
Thanks!
LEFT JOINS
, because there may not be a vote.SUM(USERVOTES.PROFILE_ID={cost}) as Xvoted
will show if a specific user voted.USERVOTES
table representative of a like?...if so, then theUSERVOTES
table will never store dislikes or other types of voting?USERLIKES
- because there is only one kind of vote (a like)USER
. In fact, the likes describe the posts not the users so if you're looking for a prefix, I'd actually name itPostLikes
to be more clear.