Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2 selects in SQL

Tags:

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!

like image 298
M.V. Avatar asked Oct 05 '11 09:10

M.V.


People also ask

How do you find the difference between two SELECT statements in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

What is the difference between SELECT * and SELECT 1?

Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.

How can I compare two table results in SQL?

Comparing the Results of the Two Queries Let us suppose, we have two tables: table1 and table2. Here, we will use UNION ALL to combine the records based on columns that need to compare. If the values in the columns that need to compare are the same, the COUNT(*) returns 2, otherwise the COUNT(*) returns 1.

How do you compare two queries performance?

We can compare the execution plan of the already saved query execution plan as well. To do so, just open the query execution plan in SQL Server Management Studio 2016. Once opened, right click on the execution plan, and click on the Showplan compare.


1 Answers

Try this:

SELECT *  FROM table WHERE value NOT IN ( SELECT value FROM table WHERE user = 1) 
like image 161
Mahmoud Gamal Avatar answered Oct 19 '22 16:10

Mahmoud Gamal