Joins got me down
December 24, 2008 1:03 PM
Subscribe
Yet another MySQL join question.
Ok, so I have a hard time conceptualizing all but the most basic MySQL joins and thus I just can't seem to wrap my head around how to do this particular task.
Lets say I have a page I'm going to display (which is identified by its "item_id") and along with the page I display comments pulled from my database.
So if I would have two tables:
comments, which consists of three fields:
serial_number | item_id | comment_body
(serial_number is a unique auto incrementing key to identify comments, item_id is the page the comment belongs to and comment body is self explanatory)
Every time a user reads a comment I mark it off in its own table called mark_as_read, which also consists of three fields:
user_name | comment_serial | item_id
(primary key is user_name+comment_serial)
What I'm having a problem with is given a particular user I want to generate a list of all the item_ids that have at least one comment that hasn't been marked as read by that user.
So if given a 'user_name' I'd want to generate a list of the 15 most recent 'comments.item_id's where there exists a 'comments.serial_number' that isn't listed in 'mark_as_read' paired with the provided 'user_name'.
I know how to do basically the opposite, pull up a list of all the item_ids that the user *has* read at least one comment from:
SELECT DISTINCT comments.item_id
FROM comments, mark_as_read
WHERE mark_as_read.user_name = "$user_name" AND comments.serial_number = mark_as_read.comment_serial
ORDER BY comments.serial DESC LIMIT 15
But I honestly have to idea how to formulate a join to do this task, when I want to find all the items where the user hasn't read at least one comment.
Any folks more clever then myself care to give some advice?
Thanks much!
Jeremy
posted by Jezztek to computers & internet (11 comments total)
2 users marked this as a favorite
SELECT DISTINCT comments.item_id FROM comments
WHERE comments.user_name = "$user_name" AND
comments.serial_number NOT IN (SELECT mark_as_read.serial_number FROM mark_as_read WHERE mark_as_read.user_name="$user_name")
Subqueries require MySQL 5, I think, though so this might not work for you.
You could probably also do this by LEFT JOINing the mark_as_read table against the comments table and then checking for places where the mark_as_read.serial_number is NULL (indicating no matching record in the mark_as_read table).
posted by toomuchpete at 1:28 PM on December 24, 2008