在查询中使用联接时出错

时间:2013-06-28 12:45:49

标签: mysql sql

我有这个问题:

SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEFT JOIN `employees` c ON a.employee_code = c.code
WHERE b.type = "Design"
AND c.code NOT IN(
    SELECT * FROM `employee_activities` a
        LEFT JOIN `activity` b ON a.activity_code = b.code
        LEFT JOIN `employees` c ON a.employee_code = c.code
        WHERE b.type = "Testing"
)
GROUP BY c.code

我收到此错误:

#1241 - Operand should contain 1 column(s)

我想要让所有至少有一项活动类型为“设计”的员工和没有“测试”类型活动的员工。

我有一个有效的查询,但我希望它能用于连接。

这有效:

SELECT c.name FROM `employee_activities` a, `activity` b, `employees` c
WHERE a.activity_code = b.code
AND a.employee_code = c.code
AND b.type = "Design"

AND c.code NOT IN(
    SELECT c.code FROM `employee_activities` a, `activity` b, `employees` c
        WHERE a.activity_code = b.code
        AND a.employee_code = c.code
        AND b.type = "Testing"
)
GROUP BY c.code

我在带连接的sql上做错了什么?

5 个答案:

答案 0 :(得分:7)

对于不在子查询中 - 它应该只包含一列 - 例如

SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEFT JOIN `employees` c ON a.employee_code = c.code
WHERE b.type = "Design"
AND c.code NOT IN(
    SELECT b.employee_code FROM `employee_activities` a
        LEFT JOIN `activity` b ON a.activity_code = b.code
        LEFT JOIN `employees` c ON a.employee_code = c.code
        WHERE b.type = "Testing"
)
GROUP BY c.code

答案 1 :(得分:3)

您的查询

AND c.code NOT IN(
   SELECT * FROM `employee_activities` a
...

尝试将c.code与子查询中的所有列进行比较。你想要的可能是什么;

AND c.code NOT IN(
    SELECT c.code FROM `employee_activities` a

此外,您的LEFT JOIN;

出现问题
LEFT JOIN `activity` b ON a.activity_code = b.code
...
WHERE b.type = "Design"

当您将左边加入的列与WHERE子句进行比较时,它基本上将整个连接转换为INNER JOIN。由于您的原始查询似乎使用内部联接,这应该没问题,但您也可以将其更改为;

SELECT * FROM `employee_activities` a
JOIN `activity` b ON a.activity_code = b.code AND b.type='Design'
LEFT JOIN `employees` c ON a.employee_code = c.code

答案 2 :(得分:2)

你的问题在于这一部分:

AND c.code NOT IN(
SELECT * FROM

你不能在这里查看c.code是否在返回的字段值列表中,并且必须在select中指定一个字段。

答案 3 :(得分:2)

问题出在本节:

AND c.code NOT IN( 
    SELECT * FROM `employee_activities` a

您无法在该嵌套查询中SELECT *。您需要选择一个与c.code进行比较的列。你需要这个:

AND c.code NOT IN( 
    SELECT c.code FROM `employee_activities` a

答案 4 :(得分:2)

做到这一点:

SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEFT JOIN `employees` c ON a.employee_code = c.code
WHERE b.type = "Design"
AND c.code NOT IN(
    SELECT c.code FROM `employee_activities` a
        LEFT JOIN `activity` b ON a.activity_code = b.code
        LEFT JOIN `employees` c ON a.employee_code = c.code
        WHERE b.type = "Testing"
)
GROUP BY c.code

在此处,您应该将数据与代码列进行比较,*将获取所有记录。