Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "!=" not the opposite of "="? [closed]

Tags:

sql

mysql

Why if I put = it brings me the correct result and when I put != it brings me the full list instead of the different ones.

SELECT     * 
FROM      library, crime_data 
WHERE     crime_data.id=$oreo 
AND       crime_data.isbn != library.isbn 
AND       crime_data.visibility='0' 
GROUP BY  library.isbn

What am I doing wrong?

like image 230
Daniel Forbes Avatar asked Dec 05 '25 20:12

Daniel Forbes


2 Answers

You have to think conceptually of what SQL is doing from a set theory viewpoint. When you join two table, the concept is a Cartesian Join – each row of table A is joined with each row of table B. So if you have table of 10 rows and a table of 20 rows and join them, you get a join of 200 rows.

Now when you select using the “=” only rows where the values are equal, usually few, are selected. When you use “!=” it select all the OTHER rows.


Edit to answer comment "how should it be".

Select *
From library
Where Not Exists 
    (
        Select 1 
        From  crime_data 
        Where crime_data.isbn = library.isbn 
    )
like image 190
asantaballa Avatar answered Dec 08 '25 10:12

asantaballa


The way != and = relate is easy to see with a simple example:

SELECT
    1=1,
    1=2,
    1=NULL,
    NULL=NULL,

    1<>1,
    1<>2,
    1<>NULL,
    NULL<>NULL

(I'm using the standard <> operator rather than the MySQL specific one !=, but they're equivalent).

+-----+-----+--------+-----------+------+------+---------+------------+
| 1=1 | 1=2 | 1=NULL | NULL=NULL | 1<>1 | 1<>2 | 1<>NULL | NULL<>NULL |
+-----+-----+--------+-----------+------+------+---------+------------+
|   1 |   0 |   NULL |      NULL |    0 |    1 |    NULL |       NULL |
+-----+-----+--------+-----------+------+------+---------+------------+

So the union of rows where crime_data.isbn = library.isbn and crime_data.isbn != library.isbn does not contain the row total; it excludes all rows where there's at least one NULL operator.

like image 23
Álvaro González Avatar answered Dec 08 '25 10:12

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!