mysql - 如何修复错误代码 1241:操作数应在 mysql 查询中包含 1 列?
问题描述
select firstName, lastName from students, courses, registration
where students.studentID = registration.studentID
and courses.courseCode = registration.courseCode
and gender = 'M' and courseName = 'Database Systems'
in(select firstName, lastName
from students, courses, registration
where students.studentID = registration.studentID
and courses.courseCode = registration.courseCode
and gender = 'M' and courseName = 'C++');``
我需要找到同时学习过数据库系统和 C++ 的男学生,为此我需要加入学生、注册和课程表,
解决方案
由于您使用in
运算符的方式,您的查询失败,这需要左侧的列名或表达式。
根据您对目标的描述,我怀疑您的查询可以重写为使用exists
具有相关子查询的条件进行过滤,如下所示:
select
firstName,
lastName
from students s
where
gender = 'M'
and exists(
select 1
from courses c
inner join registration r on c.courseCode = r.courseCode
where
c.courseName = 'Database Systems'
and s.studentID = r.studentID
)
and exists(
select 1
from courses c
inner join registration r on c.courseCode = r.courseCode
where
c.courseName = 'C++'
and s.studentID = r.studentID
)
另一种可能的解决方案是使用聚合,并带有一个having
用于过滤的子句:
select s.firstName, s.lastName
from students s
inner join registration r
on s.studentID = r.studentID
inner join courses c
on c.courseCode = r.courseCode
and c.courseName in ('Database Systems', 'C++' )
where s.gender = 'M'
group by s.studentID, s.firstName, s.lastName
having count(distinct c.courseName) = 2
推荐阅读
- sql - 当两列具有相同的值时如何获取最后一条记录?
- python - 使用矩阵形式的约束的 Python Pulp 线性规划
- shiny - 我们可以把过滤器移到右边吗
- android - 按意图过滤器类别过滤服务
- python - Tkinter:拖动选择区域,从选定区域获取图像
- python - 在没有循环的情况下访问 django 模板中的元组值
- macos - SFSpeechRecognizer 段时间戳每分钟从零开始
- javascript - 集成 d3.js 趋势图(面积+线)作为数据工作室社区可视化
- azure-bot-service - Azure QnA 合并相同的问题
- reactjs - 使用 React 在 Google 地图中添加和删除多个多边形 - 让 Refs 正确