How to create search in MySQL that returns unmatched rows?

5

I'd like to know how I can do a search that returns records that are not part of the search condition.

For example, consider the situation where there is a database of a movie store with the cliente table and the aluguel table. The cliente table has a cliente_id tuple and the aluguel table has a cliente_id tuple.

What I want is to see the name of the clients who never rented a movie, that is, I wanted my query to return all the names that did not satisfy the script below:

'select first_name, last_name from customer
inner join rental on customer.customer_id = rental.customer_id;'
    
asked by anonymous 24.01.2016 / 05:18

3 answers

8

Just use a LEFT JOIN , and check which relationships return null:

SELECT nome, filme_id
   FROM cliente
   LEFT JOIN aluguel ON cliente.cliente_id = aluguel.cliente_id
   WHERE aluguel.cliente_id IS NULL;

See working in SQL Fiddle .

Explanation:

The LEFT JOIN causes all values in the left table to return, with or not corresponding to the value on the right.

So, WHERE aluguel.cliente_id IS NULL causes query to return only those cases where there is no movie bound to that client.


Understanding the types of join :

It's worth a read on this question to learn more about Joins :

  

What's the difference between INNER JOIN and OUTER JOIN?

A properly crafted join can prevent the use of subqueries on a variety of occasions.

    
24.01.2016 / 22:04
2

You can try using NOT IN ()

SELECT first_name, last_name FROM customer WHERE NOT IN(
    select first_name, last_name from customer
    inner join rental on customer.customer_id = rental.customer_id
);

There is not much to explain because the function name is suggestive not in - > " not in ... "

    
24.01.2016 / 06:11
1

There are several ways you can do this, I will demonstrate 3 here but it is important to take into account that using subselect or subquery can impair performance so whenever possible choose to avoid them.

Using NOT EXISTS together with a SUBSELECT

SELECT first_name, last_name
FROM custumer
WHERE NOT EXISTS
   (
   SELECT NULL
   FROM rental
   WHERE rental.customer_id = custumer.customer_id
   LIMIT 1
)

See the example working: SQLFIDDLE

Using NOT IN together with a SUBSELECT

SELECT first_name, last_name 
FROM custumer 
WHERE custumer.customer_id NOT IN
(
   SELECT rental.customer_id
   FROM rental
   WHERE rental.customer_id = custumer.customer_id
)

See the example working SQLFIDDLE

Using LEFT JOIN in conjunction with condition IS NULL

SELECT first_name, last_name 
FROM custumer
LEFT JOIN rental 
   ON custumer.customer_id = rental.customer_id
WHERE rental.customer_id IS NULL;

See the example working: SQLFIDDLE

    
23.10.2017 / 16:03