Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the relative complement of a table B in a table A (A \ B) in an SQL-Query?

Tags:

sql

select

mysql

I've got two tables:

  1. subjects: [id, ...]

  2. categories: [subject.id, ...]

I want to select all subjects from table #1 without the entries in #2 (categories).

Any tips appreciated (:

best regards

like image 693
d.hill Avatar asked Feb 11 '11 11:02

d.hill


People also ask

What is SQL Outfile?

INTO OUTFILE is the complement of LOAD DATA . Column values are written converted to the character set specified in the CHARACTER SET clause. If no such clause is present, values are dumped using the binary character set. In effect, there is no character set conversion.

How do I return a select statement from a function in MySQL?

MySQL stored functions only return a single scalar value. They cannot return result sets. Functions can be used in a scalar expression context. You can use a stored procedure to return a result set, but you can't use it in an expression.

What is select into MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.


2 Answers

Sachin's already provided a correct answer, but you can do it with join syntax as well:

SELECT
  subjects.*
FROM
  subjects
LEFT OUTER JOIN
  categories
ON
  subjects.id = categories.subject_id
WHERE
  categories.subject_id IS NULL
like image 94
Dan Grossman Avatar answered Oct 06 '22 21:10

Dan Grossman


select * from subjects where id not in (select subject.id from categories )
like image 43
Sachin Shanbhag Avatar answered Oct 06 '22 19:10

Sachin Shanbhag