在两个表中查找值

时间:2018-04-29 16:36:11

标签: mysql sql join

我有两张桌子'学生'和'book'

学生有 - Student_ID |名字|年龄

书有 - ISBN | book_name |主题| student_id数据

我需要找到 数学和的学生的 student_ID,student_name,age 计算机 在书表中的相对主题列中。表格没有加入btw。任何人都可以向我显示正确的SQL查询吗?

2 个答案:

答案 0 :(得分:1)

您可以在表和过滤器之间使用连接来检查主题是否包含2个不同的对象

select a.student_ID,a.student_name,a.age
from  student a
inner join book b  on a.student_ID = b.student_ID 
where b.subject in ('mathematics', 'computer')
group by a.student_ID,a.student_name,a.age 
having count(distinct subject) = 2

答案 1 :(得分:0)

select  a.student_ID
,       a.student_name
,       a.age
from    student a
join    book b  
on      a.student_ID = b.student_ID 
where   b.subject like '%mathematics%'
        or b.subject like '%computer%'
group by
        a.student_ID
,       a.student_name
,       a.age
having  count(distinct case when b.subject like '%mathematics%' then 1
              when b.subject like '%computer%' then 2 end) = 2