问题
I need a hint in order to solve this SQL (self-join) problem:
a table, with columns value
and category
id || value || category || foo
------------------------------------
1 || 1 || a || 1
2 || 2 || a || 4
3 || 3 || a || 2
4 || 0 || b || 2
5 || 1 || b || 1
6 || 2 || b || 4
7 || 3 || b || 2
8 || 4 || b || 2
9 || 5 || b || 1
10 || 5 || b || 4
11 || 6 || b || 2
12 || 99 || z || 2
I would like to compare all values from category b
and all values from category a
and get all values that are in b
and not in a
or their id
, so:
(0,1,2,3,4,5,5,6) "compare" (1,2,3) => (0,4,5,5,6)
回答1:
ANSI SQL:
SELECT
*
FROM
tbl
WHERE
category = 'b'
AND value NOT IN (SELECT value FROM tbl WHERE category = 'a')
See it live here.
回答2:
Start analyzing your task: "get all values that are in b and not in a or their id"
- get all values >
SELECT value FROM mytable
- that are in b >
WHERE category = 'b'
- and not in a >
AND value NOT IN (SELECT value FROM mytable WHERE category = 'a')
- or their id - what should this mean?
来源:https://stackoverflow.com/questions/15899022/sql-column-compare-in-the-same-table-self-join