Get values from one table that are not contained in another

2

I would like to know how I can get values from a mysql database where the data obtained must be in one table and not in another.

For example: I want all equipment (table equipment) that is not reserved (table reservations)

    
asked by anonymous 08.04.2015 / 22:10

2 answers

7

You do not give much information but if I understood correctly this should do what you want:

SELECT * FROM equipamentos e
WHERE e.id NOT IN (SELECT equipamentoId FROM reservas);  

I start from the beginning that in the reservations table has the id of the equipment that is reserved.

See it working on SQLFiddle

Another way to do the same:

SELECT * FROM equipamentos e
WHERE NOT EXISTS (SELECT * FROM reservas r WHERE e.id = r.equipamentoId);

See working in SQLFiddle

A little explanation:

A SELECT only returns the rows that make the WHERE clause true.

In the first example, each machine id is checked if it is not NOT IN ) in the list returned by the sub-query SELECT equipamentoId FROM reservas . If it is not, the WHERE clause is true and SELECT returns this line.

In the second example, each machine id is checked for NOT EXISTS in the reservations table. NOT EXISTS is true If the sub-query SELECT * FROM reservas r WHERE e.id = r.equipamentoId does not return rows, the WHERE clause is true, and SELECT returns this line.

    
08.04.2015 / 23:12
1

Another way to get this information is through the LEFT JOIN or RIGHT JOIN Note:

Table A contains the fields a, b, c Table B contains the fields a, b, c, d, e, f

SELECT A.a, A.b, A.c, B.d, B.e, B.f
  FROM A
 RIGHT JOIN B ON A.a = B.a AND A.b = B.b AND A.c = B.c
 WHERE B.d IS NULL OR B.e IS NULL

Note that, other than the IN criterion that was used in the previous response, this method accepts more fields in the WHERE

This method is very common when we try to compare two or more tables that have similar information

    
29.04.2015 / 04:24