SQL SELECT DISTINCT子查询错误:1241

时间:2015-11-11 19:02:55

标签: mysql sql subquery union mysql-error-1241

我正在处理包含SELECT DISTINCT和子查询的长查询。它部分有效,但放在一起时却没有。我收到一个错误:1241 - 操作数应该包含1列,我不明白为什么。任何帮助将不胜感激。

这是我的代码:

SELECT p.projId, pc.company, s.staffId, s.fName, s.lName
    FROM projects AS p
    INNER JOIN projCorp AS pc ON p.projId = pc.projId
    INNER JOIN projStaff AS ps ON p.projId = ps.projId
    INNER JOIN staff AS s ON ps.staffId = s.StaffId
    WHERE p.projId = '9' AND s.company = pc.company
UNION
    SELECT DISTINCT p.projId, pc.company, "NA", "NA", "NA"
    FROM projects AS p
    INNER JOIN projCorp AS pc ON p.projId = pc.projId
    INNER JOIN projStaff AS ps ON p.projId = ps.projId
    WHERE p.projId = '9' AND pc.company NOT IN (SELECT p.projId, pc.company, s.staffId, s.fName, s.lName
        FROM projects AS p
        INNER JOIN projCorp AS pc ON p.projId = pc.projId
        INNER JOIN projStaff AS ps ON p.projId = ps.projId
        INNER JOIN staff AS s ON ps.staffId = s.StaffId
        WHERE p.projId = '9' AND s.company = pc.company);

没有NOT IN子查询,我得到了这个结果:

result without NOT IN subquery

NOT IN子查询的原因是要删除没有关联工作人员的第三个重复条目。结果应该只有图片结果字段中的前两个条目。

3 个答案:

答案 0 :(得分:3)

剪断:

... WHERE p.projId = '9' AND pc.company NOT IN (
        SELECT p.projId, pc.company, s.staffId, s.fName, s.lName
        FROM projects AS p ....
    )

您尝试在company not in时选择,但在not in查询中指定了多个选定的行。只需选择company

即可
... WHERE p.projId = '9' AND pc.company NOT IN (
        SELECT pc.company
        FROM projects AS p ....
    )

答案 1 :(得分:2)

如果要保留给定项目的所有行,请使用upload_status.php

left join

这似乎比复杂的SELECT p.projId, pc.company, s.staffId, s.fName, s.lName FROM projects p LEFT JOIN projCorp pc ON p.projId = pc.projId LEFT JOIN projStaff ps ON p.projId = ps.projId LEFT JOIN staff s ON ps.staffId = s.StaffId AND s.company = pc.company WHERE p.projId = '9'; 查询更明智。如果真的需要,您可以使用unioncoalesce()值转换为NULL

我对哪个表应该首先感到困惑 - 但我认为所有公司都与所有项目相对。如果是,则这是'NA'子句,没有FROM

WHERE

答案 2 :(得分:0)

您的IN列表应包含来自一列pc.company的值。但是您的IN列表包含多列的值。