简体   繁体   中英

Give the Match between Three Tables SQL

I am writing a script to check if the news are seen or not by multiple users In order to check new news that never checked by that user. I think that a service keep asking the server to give the News that never been read by the User. But i didn't know how to write about it.( I've used the Cartesian product but that didn't work). In other Words, how to check if the user didn't read this news and give me a way to provide a notification. If anyone can help me Please? These are thethree tables in my database:Users,News,and Seen.

This is the Users table:

User_ID | User_Name
--------------------
1       | John
2       | Carl
3       | Tomas
4       | Adam
5       | Nancy

And the News Table:

News_ID | News_Text
--------------------
1       | Hello World
2       | This is My car
3       | I had Ate pizza
4       | No Body Want Programming
5       | C++ Programming

Also this is the Seen Table:

ID   | User_Id  | News_Id
---------------------------
1    |  1       | 2
2    |  1       | 3
3    |  4       | 1
4    |  5       | 3
5    |  1       | 4

This should get the News_ID's of all news that "UserIdYouCareAbout" hasn't seen (replace <UserIdYouCareAbout> with the User_ID you're querying against).

SELECT News.News_ID AS 'Unseen News ID'
FROM News 
    LEFT JOIN Seen ON Seen.News_ID = News.News_ID AND Seen.User_ID = <UserIdYouCareAbout>
WHERE
    Seen.ID IS NULL
SELECT *
FROM News
WHERE News_ID NOT IN (
    SELECT News_Id FROM Seen WHERE User_Id = <userID>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM