简体   繁体   中英

MySQL select specific entry from a table which is not in another table

I have a problem in MySQL when trying to select specific entry from table which is not in another table. I know this sentence sounds nuts but here is an example what I am trying to do.

Table users:

    user_id,username,password (plus other columns not important to this)

Table articles:

    article_is,user_id,content (plus others)

Table views (used to store data if user viewed specific article):

   view_id,article_id,user_id,date

Now, I am trying to select those users who has NOT read a specific article, for example article with id 10. So they have no entry in the views table.

I hope it makes more sense now. Thanks for your answers. V.

Try this:

SELECT user_id
FROM users
WHERE user_id NOT IN (
  SELECT user_id
  FROM views
  WHERE article_id = 10
)
SELECT user_id FROM users u
LEFT JOIN views v ON v.user_id=u.user_id AND v.article_id = 10
WHERE v.user_id IS NULL

doing NOT IN queries are not typically great for performance... instead, using LEFT JOIN and looking for NULL would be better.

select 
      u.User_ID
   from 
      Users U
         LEFT JOIN Views V
            on U.User_ID = V.User_ID 
           AND v.Article_ID = 10
   where
      V.User_ID IS NULL

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