D
D
driverx182017-09-24 22:47:04
MySQL
driverx18, 2017-09-24 22:47:04

How to list a user's unread posts?

There is a table users
There is a table articles
After the user on the site goes to the news, it will automatically be as read. That is, there is a read_articles table.
Actually, its structure is:

id | article_id | user_id

How can I display to the user with id #2 (let's say) all his unread articles? Here I have one sketch (it displays those articles that have been read):
SELECT articles.id, articles.title, articles.text FROM articles INNER JOIN read_articles ON articles.id = read_articles.article_id WHERE read_articles.user_id = 2;

I thought, in order to display articles which are unread, it is necessary to put the sign not =, but != in that piece of code (well, that is, like this):
SELECT articles.id, articles.title, articles.text FROM articles INNER JOIN read_articles ON articles.id != read_articles.article_id WHERE read_articles.user_id = 2;

But for some reason, he displays all the records 3-4 times.
Actually, the question is how effective is how I do it now, and who can help display UNREAD articles? It seems to me that the way I did it is completely inefficient, wrong JOIN, and something like that

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem0071, 2017-09-24
@driverx18

In the second option, you have tables connected incorrectly, so there are problems.
There is a NOT IN
construct . Something like this:

SELECT articles.id, articles.title, articles.text FROM articles WHERE articles.id NOT IN ( SELECT articles.id FROM articles WHERE user_id = some_id )

I
Ilya Gerasimov, 2017-09-24
@Omashu

SELECT articles.id, articles.title, articles.text FROM articles WHERE id NOT IN(SELECT article_id  FROM read_articles WHERE user_id = ?)

Well, this type

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question