简体   繁体   中英

Difference between 2 selects in SQL

I have one data table:

--------------------
ID |  user | Value
--------------------
1  |  1    | 1
--------------------
2  |  1    | 2
--------------------
3  |  2    | 3
--------------------
4  |  2    | 2
--------------------
5  |  3    | 4
--------------------
6  |  3    | 2
--------------------

I would like to SELECT all rows where value is different comparing to user 1 so the result would be rows with IDs 3 (value is 3) and 5 (value is 2)

I would do something like this (will call it A)

SELECT * FROM table WHERE user = 1

and get all the rows from user 1. Than I would select (will call it B)

SELECT * FROM table WHERE user != 1

and get all other rows. And than I would compare them WHERE A.value != B.value .

I'm stuck on how to merge everything together...

Please help!

Try this:

SELECT * 
FROM table
WHERE value NOT IN ( SELECT value FROM table WHERE user = 1)

The relational operator is indeed 'difference', Oracle has the keyword MINUS , Standard SQL has the keyword EXCEPT eg

SELECT value 
  FROM table 
EXCEPT
SELECT value 
  FROM table 
 WHERE user = 1;

Sadly, MySQL doesn't have any such an operator, you have to use other SQL constructs eg NOT IN <table expression> :

SELECT value 
  FROM table
 WHERE value NOT IN ( SELECT value
                        FROM table
                       WHERE user = 1 );

select * from table where value not in (select value from table where user = 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM