是否有任何查询说


  “在……中,但不在……中。”?


假设我有一张有关“双重代理人”的表格。

该表具有名称,国籍和年龄。

+-------------------------+
| Name    Nationality Age |
+-------------------------+
| Jony    US          20  |
| Jony    China       20  |
| Adam    Argentina   25  |
| Lukas   China       39  |
| Lukas   US          39  |
+-------------------------+


然后,我计划为所有具有中国国籍而不是美国的特工输出一份清单。

我写了什么


  从代理人中选择姓名,其中国籍='中国',国籍!='美国'


如预期的那样,它没有打印任何内容,因为它是错误的。

我知道也许这是一个愚蠢的答案,但是有人可以纠正我吗?谢谢。

最佳答案

我将使用聚合和having进行此操作。我认为最清晰的方法是:

select name
from agent
group by name
having sum(nationality = 'China') > 0 and
       sum(nationality = 'US') = 0;


肯定还有其他方法。这是不需要select distinctgroup by的一个:

select a.name
from agent a
where a.nationality = 'China' and
      not exists (select 1 from agent a2 where a2.name = a.name and a2.nationality = 'US');


使用agent(nationality, name)agent(name, nationality)上的索引,这可能具有最佳性能。

关于mysql - MySQL查询:是否有任何查询,例如“但不能在<空白>”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37105799/

10-16 13:24
查看更多