SQL Column compare in the same table (self-join)

北城以北 提交于 2019-12-25 07:25:45

问题


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"

  1. get all values > SELECT value FROM mytable
  2. that are in b > WHERE category = 'b'
  3. and not in a > AND value NOT IN (SELECT value FROM mytable WHERE category = 'a')
  4. or their id - what should this mean?


来源:https://stackoverflow.com/questions/15899022/sql-column-compare-in-the-same-table-self-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!