简体   繁体   中英

select records which have different values in the same column and different values in another column without subqueries

I have this table:

item        year
----        ----
1           1999 
2           1999
3           1999 
2           2000 
4           2000 
2           2001
3           2001
4           2001
5           2001

And I need this result (with 1999 selected)

item        year
----        ----
4           2000
4           2001
5           2001

To sum up, I need to obtain new items which aren't in 1999, but which are defined in another different year (this is for adding them with another query later).

I'm using an old MySQL version and I'm not able to use subqueries . Is there any compatible solution?

What about something like this

SELECT t1.item, t1.year from table as t1
LEFT JOIN table as t2 ON t2.item = t1.item AND t2.year = 1999
WHERE t2.item IS NULL

In "english" it means, select all the items from my table. Then for each item try to find if they are in the table with the year 1999, else put NULL. Then you just have to say "keep the elements that do not have a matching element in t2.

Not sure if my explanation is better anyway

EDIT: you of course need to replace table with the name of your own table. I tested it on a small example and it seems to work.

EDIT2 : If you look at the result of the LEFT JOIN you would have something like this :

t1.item     t1.year    t2.item     t2.year
----        ----       ----        ----       
1           1999       1           1999
2           1999       2           1999
3           1999       3           1999
2           2000       2           1999
4           2000       NULL        NULL
2           2001       2           1999
3           2001       3           1999
4           2001       NULL        NULL
5           2001       NULL        NULL

Then if you add WHERE t2.item IS NULL you only keep the ones not having a year 1999 in the table. Is it a better way to understand it?

select t2.item, t2.year
from mytable t1
left join mytable t2 
    on t2.year > t1.year 
    and t2.item != t1.item
where t1.year = 1999
and t2.item is null

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