簡體   English   中英

如何修復錯誤代碼 1241:操作數應在 mysql 查詢中包含 1 列?

[英]How do I fix Error Code 1241: Operand should contain 1 column(s) in mysql query?

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

您的 in 子句缺少一些列嘗試

select 
   firstName, lastName 
from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'Database Systems' 
and students.studentID
in (select studentID 
from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'C++');

使用HAVING子句可以更輕松地編寫此查詢,以檢查學生從集合('Database Systems'、'C++')中選擇的課程數量是否為 2:

SELECT s.studentID, s.firstName, s.lastName 
FROM students s
JOIN registration r ON s.studentID = r.studentID 
JOIN courses c ON c.courseCode = r.courseCode 
WHERE s.gender = 'M' AND c.courseName IN ('Database Systems', 'C++')
GROUP BY s.studentID, s.firstName, s.lastName
HAVING COUNT(DISTINCT c.courseName) = 2

請注意,我已經用ON條件以首選樣式重寫了您的JOIN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM