A
A
andreyblind2016-05-30 22:58:31
MySQL
andreyblind, 2016-05-30 22:58:31

MySQL database query with nested logical negation?

Good day. There are three tables:
books (id, title)
users (id, first_name, last_name, age)
users_books (id, user_id, book_id)
The users_books table contains information about books purchased by users. You must select a list of users who have not purchased a book with a specific title.
My request:

SELECT 
 DISTINCT users.first_name, 
 users.last_name, 
 users.id 
FROM 
 users 
 INNER JOIN users_books ON users.id = users_books.user_id 
WHERE 
 users_books.user_id NOT IN (
  SELECT 
   `user_id` 
  FROM 
   `users_books` 
  WHERE 
   users_books.book_id = (SELECT id FROM books where title = "Book")
 ) 
GROUP BY 
 users_books.user_id

Is it possible to fulfill the request in an optimal way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly, 2016-05-30
@taliban

Normal query, only WHERE needs to be tweaked a bit

SELECT 
 DISTINCT users.first_name, 
 users.last_name, 
 users.id 
FROM 
 users 
 INNER JOIN users_books ON users.id = users_books.user_id 
WHERE 
 users_books.book_id NOT IN (SELECT id FROM books where title = "Book" ) 
GROUP BY 
 users_books.user_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question