简体   繁体   中英

how to choose value in 1 column that must have 2 values in another - sql?

table:

id   lesson
11  11 A
8   11 B
4   11 A
4   11 A
2   11 A
6   11 A
5   11 A
13  11 A
11  11 B

the id 11 has both taught in classroom 11A, 11B. How to select the ids that have both values 11a,11b?

I tried this with no luck:

select id from table where lesson in '11A' and lesson in '11B' 

because it gives empty table, because it can't be both 11a and b at the same time.

for obtain the id with both the lesson

if could try using a subquery for the involved id and the count if the id have more then a result

select id 
FROM (
    select id 
    from my_table 
    where lesson in ('11A', '11b')
) t 
group by id 
having count(*) = 2

If it's exectly two values you can make an inner join

select a.id 
from myTable a
inner join myTable b
on a.id = b.id 
and a.lesson = '11 A' and b.lesson = '11 B'

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