简体   繁体   English

SQL查询中的ALL运算符子句

[英]ALL operator clause in SQL query

I have this table schema. 我有这个表模式。

Machine​(machine_id​, size)
Operator​(operator_id​, name)
OperationLog​(machine_id, operator_id, date, comment)
  ​machine_id: FK(Machine)
  operator_id: FK(Operator)

Assuming I want a query that only gives me the name of the operators that operated all machines with size above 5m2 假设我想要一个查询,它只给我操作所有大小超过5平方米的机器的操作员的名字

Would using the ALL operator give me the desired result? 使用ALL运算符会给我想要的结果吗? As in, from the list of Machines with size above 5, Operators that have Logs must match all of those machines. 在大小超过5的机器列表中,具有日志的操作员必须匹配所有这些机器。

SELECT O.name
  FROM Operator O NATURAL JOIN OperationLog L
  WHERE L.machine_id​ = ALL (
      SELECT M.machine_id​     
      FROM Machine M  
      WHERE size >5);

Or would I need to do a "double negation" like so? 或者我需要像这样做“双重否定”?

SELECT O.name
FROM Operator O
WHERE NOT EXISTS(
   SELECT M.machine_id​
   FROM Machine M 
   EXCEPT
   SELECT L.machine_id​            
   FROM OperationLog L NATURAL JOIN Machine M      
   WHERE L.operator_id = O.operator_id
         AND size >5);

I feel I am complicating too much and there's probably a better way. 我觉得我太复杂了,而且可能有更好的方法。

Count how many different machines of (size >= 5) each operator used and compare that number to the total number of such machines: 计算每个运营商使用的(size >= 5)不同的机器数量,并将该数量与此类机器的总数量进行比较:

SELECT op.name
FROM operator op
    INNER JOIN operationlog l
        ON op.operator_id = l.operator_id
    INNER JOIN machine m
        ON l.machine_id
WHERE m.size >= 5
GROUP BY op.name
HAVING COUNT(DISTINCT m.machine_id) = (
        SELECT COUNT(*)
        FROM machine
        WHERE size >= 5
)

I am a fan of using group by and having for this purpose: 我使用的粉丝group byhaving用于此目的:

SELECT O.name
FROM Operator O JOIN
     OperationLog L
     ON L.operator_id = O.operator_id JOIN
     Machine M 
     ON L.machine_id​ = M.machine_id​ 
WHERE M.size > 5
GROUP BY O.name  
HAVING COUNT(DISTINCT M.machine_id) = (SELECT COUNT(DISTINCT M2.machine_id)
                                       FROM Machine M2  
                                       WHERE size > 5
                                      );

If there are not duplicates in the tables, then use COUNT(*) rather than COUNT(DISTINCT) . 如果表中没有重复项,则使用COUNT(*)而不是COUNT(DISTINCT)

I should note that I strongly discourage you from using NATURAL JOIN . 我应该注意,我强烈反对你不使用NATURAL JOIN It is a bug waiting to happen. 这是一个等待发生的错误。 Why? 为什么? It simply uses columns that have the same names. 它只使用具有相同名称的列。 It doesn't even use the same types. 它甚至不使用相同的类型。 For instance, most tables I create have columns for CreatedBy and CreatedAt and it would use these columns. 例如,我创建的大多数表都有CreatedByCreatedAt列,它们将使用这些列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM