5

我有这个查询:

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 上做错了什么?

4

5 回答 5

7

对于 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 = "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
于 2013-06-28T12:48:50.247 回答
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
于 2013-06-28T12:49:36.047 回答
2

你的问题出在这部分:

AND c.code NOT IN(
SELECT * FROM

您不能在此处使用 * 来查看 c.code 是否在返回的字段值列表中,并且必须在选择中仅指定一个字段。

于 2013-06-28T12:48:57.923 回答
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
于 2013-06-28T12:49:23.137 回答
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

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

于 2013-06-28T12:50:48.550 回答